不懂的话推荐看这篇博客,讲的很清楚 http://blog.csdn.net/v_july_v/article/details/7041827
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 using namespace std; 5 const int maxlen=1024; 6 char S[maxlen],T[maxlen],next[maxlen]; 7 void get_next() 8 { 9 next[0]=-1; 10 int i=0,j=-1; 11 while(i<strlen(T)-1){ 12 if(j==-1||T[i]==T[j]){ 13 i++;j++; 14 if(T[i]!=T[j]) 15 next[i]=j; 16 else next[i]=next[j]; 17 }else j=next[j]; 18 } 19 } 20 int KMP() 21 { 22 int slen=strlen(S),tlen=strlen(T); 23 get_next(); 24 int i=0,j=0; 25 while(i<slen&&j<tlen){ 26 if(j==-1||S[i]==T[j]){ 27 i++;j++; 28 }else{ 29 j=next[j]; 30 } 31 } 32 if(j==tlen) return i-j; 33 else return -1; 34 } 35 int main() 36 { 37 scanf("%s",S); 38 scanf("%s",T); 39 cout<<KMP()+1; 40 return 0; 41 }
时间: 2024-11-03 03:45:54