【KMP】AcWing831. KMP字符串
讲解
AcWing831.KMP字符串

题解
本题用find函数会超时,因为find并没有对于找到子串的情况下次使用next。
KMP改进模式
下标从1开始
#include <iostream>
#include <cstdio>
using namespace std;
const int N = 1e5 + 10, M = 1e6 + 10;
int n, m, ne[N];
char p[N], s[M];
int main()
{
cin >> n >> p + 1 >> m >> s + 1;
int i = 1, j = 0;
while(i <= n)
{
if(!j || p[i] == p[j])
{
i ++ ;
j ++ ;
if( p[i] == p[j]) ne[i] = ne[j];
else ne[i] = j;
}
else j = ne[j];
}
i = 1, j = 1;
while(i <= m)
{
if(!j || s[i] == p[j]) i ++, j ++;
else j = ne[j];
if(j == n+1) j = ne[j], printf("%d ", i - n - 1);
}
return 0;
}
下标从0开始
#include <cstdio>
#include <iostream>
using namespace std;
const int N = 1e5 + 10, M = 1e6 + 10;
char P[N], S[M];
int ne[N];
void get_next(char *p, int m)
{
int i = 0, j = -1;
ne[0] = -1;
//本来是i < m-1,但这里要求多个KMP所以我们需要知道当找到子串后的next[m]
while(i < m )
{
if(j == -1 || p[i] == p[j])
{
i ++ ;
j ++ ;
if(p[i] != p[j])
ne[i] = j;
else
ne[i] = ne[j];
}
else
j = ne[j];
}
}
void KMP(char *S, char *P, int n, int m)
{
int i = 0, j = 0;
while(i < n)
{
if(j == -1 || S[i] == P[j])
i ++, j ++ ;
else
j = ne[j];
if(j == m)
{
printf("%d ", i - m);
j = ne[j]; //当找到子串后获取next[m]
}
}
}
int main()
{
int m, n;
scanf("%d%s%d%s",&m, P, &n, S);
get_next(P, m);
KMP(S, P, n, m);
return 0;
}

浙公网安备 33010602011771号