Kuro-orzz's Library

This documentation is automatically generated by online-judge-tools/verification-helper

View on GitHub

:warning: String/KMP/test_kmp.cpp

Depends on

Code

#include "../../template.h"
#include "Kmp.h"

// AC: https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description/

class Solution {
public:
    int strStr(string haystack, string needle) {
        int n = haystack.size(), m = needle.size();
        vector<int> res = __KMP(needle, haystack);
        for (size_t i = 0; i < n; i++) {
            if (res[i] == m) return i - m + 1;
        }
        return -1;
    }
};
#line 2 "template.h"

#include <bits/stdc++.h>
using namespace std;
 
#define ll long long
#define MOD (ll)(1e9+7)
#define all(x) (x).begin(),(x).end()
#define unique(x) x.erase(unique(all(x)), x.end())
#define INF32 ((1ull<<31)-1)
#define INF64 ((1ull<<63)-1)
#define inf (ll)1e18

#define vi vector<int>
#define pii pair<int, int>
#define pll pair<ll, ll>
#define fi first
#define se second

const int mod = 998244353;

void solve();

int main(){
    ios_base::sync_with_stdio(false);cin.tie(NULL);
    // cin.exceptions(cin.failbit);
    // int t; cin >> t;
    // while(t--)
        solve();
    cerr << "\nTime run: " << 1000 * clock() / CLOCKS_PER_SEC << "ms" << '\n';
    return 0;
}
#line 2 "String/KMP/Kmp.h"

vector<int> lps(const string &s) {
    int n = s.size();
    vector<int> pi(n);
    for (int i = 1; i < n; i++) {
        int j = pi[i-1];
        while (j > 0 && s[i] != s[j]) {
            j = pi[j - 1];
        }
        if (s[i] == s[j]) j++;
        pi[i] = j;
    }
    return pi;
}

vector<int> __KMP(const string &s, const string &t) {
    int n = s.size(), m = t.size();
    if (n == 0) return {};
    vector<int> pi = lps(s);
    int j = 0;
    vector<int> ans(m);
    for (int i = 0; i < m; i++) {
        while (j > 0 && t[i] != s[j]) {
            j = pi[j - 1];
        }
        if (t[i] == s[j]) j++;
        ans[i] = j;
        if (j == n) {
            j = pi[j - 1];
        }
    }
    return ans;
}
#line 3 "String/KMP/test_kmp.cpp"

// AC: https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description/

class Solution {
public:
    int strStr(string haystack, string needle) {
        int n = haystack.size(), m = needle.size();
        vector<int> res = __KMP(needle, haystack);
        for (size_t i = 0; i < n; i++) {
            if (res[i] == m) return i - m + 1;
        }
        return -1;
    }
};
Back to top page