Files
python/TangDou/Topic/Test.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

28 lines
686 B
C++

#include <bits/stdc++.h>
using namespace std;
const int N = 1000010;
int n, m, ne[N];
char s[N], p[N];
int main() {
cin >> n >> (p + 1) >> m >> (s + 1);
// 求模式串ne数组
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) {
printf("%d ", i - n);
j = ne[j]; // 继续搜索,重置 j=ne[j]
}
}
return 0;
}