next数组用于存储模式串中元素为j位置的最大重叠度。
//KMP算法实现字符串匹配 // #include <cstdlib> #include <iostream> using namespace std; void compute_next(int* next,char const*p,int len){ int j=0; int q=next[0]=-1; --len; while(j<len) if(q==-1||p[q]==p[j]) next[++j]=++q; else q=next[q]; } char const* kmp_find(char const*t,int tlen,char const*p,int plen,int const*next){ int i=-1; int j=-1; while((i<tlen)&&(j<plen)){ if((j==-1)||(t[i]==p[j])) {++i;++j;} else j=next[j]; } if(j==plen) return t+i-plen; else return 0; } int main() { char a[100]="ahgdhjggabcabcabbacll"; char b[12]="abcabcabbac"; char const* t_; int next[11]; compute_next(next,b,11); for(int i=0;i<11;i++) cout<<next[i]<<endl; t_=kmp_find(a,100,b,11,next); if(!t_) cout<<"can not find mode string in target string!"<<endl; else cout<<"the position of mode string in target string is:"<<t_-a+1<<endl; system("PAUSE"); return EXIT_SUCCESS; }
时间: 2024-11-07 17:37:59