KMP算法(查找该字串是否存在)
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <stdlib.h> 5 #include <algorithm> 6 #include <math.h> 7 #include <vector> 8 #include <list> 9 #include <map> 10 #include <set> 11 using namespace std; 12 13 char chsum[100002],ch[100002],x[200004]; 14 int lowbit[100002]; 15 16 void kmp() 17 { 18 lowbit[0]=-1; 19 lowbit[1]=0; 20 int k=0,j=1; 21 while(j<strlen(ch)) 22 { 23 if(k==-1||ch[k]==ch[j]) 24 { 25 lowbit[++j]=++k; 26 } 27 else 28 { 29 k=lowbit[k]; 30 } 31 } 32 } 33 34 bool KMP_Index() 35 { 36 int i = 0, j = 0; 37 int slen=strlen(chsum); 38 int tlen=strlen(ch); 39 kmp(); 40 while(i < slen && j < tlen) 41 { 42 if(j == -1 || chsum[i] == ch[j]) 43 { 44 i++; j++; 45 } 46 else 47 j = lowbit[j]; 48 if(j==tlen) return true; 49 } 50 if(j == strlen(ch)) 51 return true; 52 else 53 return false; 54 } 55 56 int main() 57 { 58 while(~scanf("%s",x)){ 59 strcpy(chsum,x); 60 strcat(chsum,x); 61 scanf("%s",ch); 62 memset(lowbit,0,sizeof(lowbit)); 63 if(strlen(x)<strlen(ch)) cout<<"no"<<endl; 64 else{ 65 if(KMP_Index()) cout<<"yes"<<endl; 66 else cout<<"no"<<endl; 67 } 68 } 69 }