点击查看代码
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
string s1, s2;
int ne[N];
void get_ne() {
ne[1] = 0;
int n = s2.length();
for (int i = 2,j=0; i <= n; i++) {
while (j && s2[j+1] != s2[i]) j = ne[j];
if (s2[j+1] == s2[i]) j++;
ne[i] = j;
}
}
int main() {
cin >> s1 >> s2;
int n = s1.length(),m=s2.length();
s1 = ' ' + s1;
s2 = ' ' + s2;
get_ne();
for (int i = 1, j = 0; i <= n; i++) {
while (j && s1[i] != s2[j + 1]) j = ne[j];
if (s1[i] == s2[j+1]) j++;
if (j == m) cout << (i - m + 1) << '\n';
}
for (int i = 1; i <= m; i++) {
cout << ne[i] << ' ';
}
return 0;
}