kmp算法基础

https://www.luogu.com.cn/problemnew/solution/P3375

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int maxn=1e6+10;
 4 int kmp[maxn];
 5 char a[maxn],b[maxn];
 6 int main()
 7 {
 8     scanf("%s%s",a+1,b+1);
 9     int lena=strlen(a+1);
10     int lenb=strlen(b+1);
11     int index=0;
12     for(int i=2;i<=lenb;i++){
13         while(index&&b[i]!=b[index+1])
14             index=kmp[index];
15         if(b[index+1]==b[i]) index++;
16         kmp[i]=index;
17     }
18     index=0;
19     for(int i=1;i<=lena;i++){
20         while(index>0&&b[index+1]!=a[i])
21             index=kmp[index];
22         if(b[index+1]==a[i])
23            index++;
24         if(index==lenb) {cout<<i-lenb+1<<endl;index=kmp[index];}
25     }
26     for(int i=1;i<=lenb;i++)
27         printf("%d ",kmp[i]);
28     printf("\n");
29 }

 

posted @ 2020-02-03 10:38  古比  阅读(112)  评论(0编辑  收藏  举报