1. 程式人生 > 實用技巧 >【模板】kmp

【模板】kmp

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cmath>
 5 using namespace std;
 6 int next[1000001];
 7 void get_next(string x,int len){
 8     next[0]=-1;
 9     for(int i=1;i<=len-1;i++){
10         int j=next[i-1];
11         while((x[i]!=x[j+1])&&(j>=0
)) j=next[j]; 12 if(x[i]==x[j+1]) next[i]=j+1; 13 else next[i]=-1; 14 } 15 } 16 void kmp(string x,string y,int len_x,int len_y){ 17 int i=0,j=0; 18 while(i<=len_x-1){ 19 if(x[i]==y[j]){ 20 i++; 21 j++; 22 if(j==len_y){ 23 printf("
%d\n",i-j+1); 24 j=next[j-1]+1; 25 } 26 } 27 else{ 28 if(j==0) i++; 29 else j=next[j-1]+1; 30 } 31 } 32 } 33 int main(){ 34 string str1,str2; 35 int len1,len2; 36 cin>>str1>>str2; 37 len1=str1.size();
38 len2=str2.size(); 39 get_next(str2,len2); 40 kmp(str1,str2,len1,len2);41 }