KMP
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
int n, p[N];
string s;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> s;
n = s.size();
s = " " + s;
p[0] = -1;
for(int i = 2, j = 0; i <= n; ++i) {
for(; j >= 0 && s[i] != s[j + 1]; j = p[j]) {
}
j++;
p[i] = j;
}
for (int i = 1; i <= n; i++) {
cout << p[i] << " ";
}
return 0;
}

浙公网安备 33010602011771号