#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
const int M = 1e6 + 10;
char p[N], s[M];
int n, m;
int ne[N];
int main()
{
cin >> n >> p + 1 >> m >> s + 1; //令字符数组从下标1开始读入
//求next数组
for (int i = 2, j = 0; i <= n; i++)
{
//j不是退无可退且不相等,则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++;
//如果找完一遍p
if (j == n)
{
printf("%d ", i - n); //题目下标从0开始
j = ne[j]; //接着看j能退回哪里继续找
}
}
return 0;
}
KMP字符串
最新推荐文章于 2024-08-10 07:14:43 发布