KMP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn=1100000;
const int maxm=1100;
int nextt[maxn],len1,len2,p=0;
char s1[maxn],s2[maxm];
int main()
{
scanf("%s%s",s1,s2);
len1=strlen(s1);
len2=strlen(s2);
for(int i=1;i<len2;++i)
{
while(s2[i]!=s2[p]&&p)p=nextt[p-1];
if(s2[i]==s2[p])p++;
nextt[i]=p;
}
p=0;
for(int i=0;i<len1;++i)
{
while(s1[i]!=s2[p]&&p)p=nextt[p-1];
if(s1[i]==s2[p])p++;
if(p==len2)printf("%d\n",i-len2+2),p=nextt[p-1];
}
//for(int i=0;i<len2;++i)printf("%d ",nextt[i]);
return 0;
}
显示 Gitment 评论