AcWing 831. KMP字符串
原题链接
简单
作者:
Fxzbed
,
2024-11-04 19:41:08
,
所有人可见
,
阅读 4
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
const int M = 1e6 + 10;
int n, m, ne[N];
char p[N], s[M];
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n >> p + 1 >> m >> s + 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 - j << ' ';
j = ne[j];
}
}
return 0;
}