1 //KMP算法实现字符串匹配 2 //该算法保证字符比较次数不超过目标串字符长度的2倍 3 #include <cstdlib> 4 #include <iostream> 5 6 using namespace std; 7 8 void compute_next(int* next,char const*p,int len){//计算模式串中元素序号j的左侧最大重叠度 9 int j=0; 10 int q=next[0]=-1; 11 --len; 12 while(j<len) 13 if(q==-1||p[q]==p[j]) 14 next[++j]=++q; 15 else 16 q=next[q]; 17 } 18 19 char const* kmp_find(char const*t,int tlen,char const*p,int plen,int const*next){ 20 int i=-1; 21 int j=-1; 22 while((i<tlen)&&(j<plen)){ 23 if((j==-1)||(t[i]==p[j])) {++i;++j;} 24 else j=next[j]; 25 } 26 if(j==plen) return t+i-plen; 27 else return 0; 28 } 29 30 int main() 31 { char a[100]="ahgdhjggabcabcabbacll";//用户自编目标串 32 char b[12]="abcabcabbac";//用户自编模式串 33 char const* t_; 34 int next[11];//与b串的元素个数相同,不含null 35 compute_next(next,b,11);// 与b串的元素个数相同,不含null 36 37 cout<<"target string:"<<endl; 38 for(int i=0;a[i];i++) 39 cout<<a[i]; 40 cout<<endl; cout<<endl; 41 cout<<"mode string:"<<endl; 42 for(int i=0;b[i];i++) 43 cout<<b[i]; 44 cout<<endl;cout<<endl; 45 46 cout<<"最大重叠度计算为:"<<endl; 47 for(int i=0;i<11;i++) 48 cout<<"pi("<<i<<"):"<<next[i]<<endl; 49 cout<<endl; 50 51 t_=kmp_find(a,100,b,11,next); 52 if(!t_) 53 cout<<"can not find mode string in target string!"<<endl; 54 else 55 cout<<"the position of mode string in target string is:"<<t_-a+1<<endl; 56 system("PAUSE"); 57 return EXIT_SUCCESS; 58 }