AcWing 831. KMP字符串
原题链接
简单
作者:
F_X
,
2021-04-06 16:45:08
,
所有人可见
,
阅读 280
#include <iostream>
using namespace std;
const int N = 1e6 + 10;
char p[N], s[N];
int ne[N];
int main ()
{
int m, n;
cin >> n >> p >> m >> s ;
//求ne[N]
{ ne[0] = -1; //i主串下标 ,j模板串下标
int i = 0, j = -1;
while (i < n)
{
if(j == -1 || p[j] == p[i])
{
i++;
j++;
ne[i] = j;
}
else j = ne[j];
}
}
int i = 0, j = 0;
while(i < m)//s为主串i , p为模板串j
{
while(i < m && j < n)
{
if(j == -1 || p[j] == s[i])
{
i ++;
j ++;
}
else j = ne[j];
}
if(j == n)
{
cout << i - j << " ";
j = ne[j];
}
}
return 0;
}