这个算法一直不理解,记录一下。

#include <bits/stdc++.h>
using namespace std;

void getNext(string t, vector<int>& next) {
    int i = 0, j = -1;
    next.resize(t.size());
    next[0] = -1;
    while (i < t.size() - 1) {
        if (j == -1 || t[i] == t[j]) {
            next[++i] = ++j;
        } else {
            j = next[j];
        }
    }
}

int kmp(string s, string t, int pos) {
    int i = pos, j = 0;
    vector<int> next;
    getNext(t, next);
    while (i < s.size() && j < t.size()) {
        if (s[i] == t[j]) {
            i++;
            j++;
        } else {
            j = next[j];
        }
        if (j == -1) {
            j++;
            i++;
        }
    }
    return j >= t.size() ? i - t.size() : -1;
}

int main(int argc, char const *argv[]) {
    string s;
    string t;
    cin >> s >> t;
    printf("%d", kmp(s, t, 0));
    return 0;
}