题面
题解
KMP 模板题 ,next[i]=j 以 i 为终点的后缀和从1开始的非平凡前缀最大重合是 j ,下标从1开始
代码
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 1e6 + 10;
int n, m;
char s[N], p[N];
int ne[N];
int main() {
cin >> n >> p + 1 >> m >> s + 1;
//求ne数组,下标从1开始
for (int i = 2, j = 0; i <= n; i++) {
while (j && p[i] != p[j + 1]) j = ne[j];
if (p[i] == p[j + 1]) j++;
ne[i] = j;
}
for (int i = 1, j = 0; i <= m; i++) {
while (j && s[i] != p[j + 1]) j = ne[j];
if (s[i] == p[j + 1]) j++;
if (j == n) {
cout << i-n << " ";
j = ne[j];
}
}
return 0;
}