Files
python/TangDou/AcWing/KMP/831_2.cpp

27 lines
754 B
C++
Raw Normal View History

2025-08-30 18:35:01 +08:00
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
const int M = 1000010;
int n, m, ne[N];
char s[M], p[N];
int main() {
cin >> n >> (p + 1) >> m >> (s + 1);
for (int i = 2; i <= n; i++) {
int j = ne[i - 1]; //其实这是原始版本,代码等价变型后成为了831_1.cpp
// j的含义:指向当前位置前一位的失配指针位置
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) {
printf("%d ", i - n);
j = ne[j];
}
}
return 0;
}