您的位置:首页 > 其它

KMP算法初步理解

2012-02-26 17:00 218 查看
#include<iostream>

#include<cstring>

using namespace std;

int *GetNext(char *t){

int tlen=strlen(t);

int *next=new int[tlen];

if(!next) return 0;

next[0]=-1;

int i=0,j=next[i];

while(i<tlen){

if(j==-1 || t[i]==t[j]){

i++;

j++;

next[i]=next[i-1]+1;

}

else

j=next[j];

}

return next;

}

int StrIndex_KMP(char *s,char *t,int pos){

//从串s下标为pos开始找首次与串t相等的子串,next数组中为next函数的相关值

int *next=GetNext(t);

int slen,tlen;

slen=strlen(s);tlen=strlen(t);

int i,j;

i=pos; j=0;

while(i<slen && j<tlen){ //没遇到结束符

if(j==-1 || s[i]==t[j]){

i++;

j++;

}

else

j=next[j];//右滑

}

delete []next; //必须加这一步,否则无法释放内存导致程序异常终止

next=NULL; //安全,哥是被指针搞怕了

if(j==tlen)

return i-tlen;//匹配成功,返回子串首字符的下标

else

return -1;//匹配失败返回-1

}

int main(){

char s[1000],t[1000];

while(cin>>s>>t){

if(StrIndex_KMP(s,t,0)==-1)

cout<<"匹配失败"<<endl;

else

cout<<StrIndex_KMP(s,t,0)<<endl; //输出匹配的下标

}

system("pause");

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: