串的模式匹配KMP算法

来源:互联网 发布:java agent 做监控 编辑:程序博客网 时间:2024/05/18 10:14


#include<iostream>
using namespace std;




typedef struct
{
char*ch;
int length;
}SString;
int Ass(SString &H,char *sh){
int i=0;
while(sh[i]) i++;
H.ch=(char*)malloc((i+1)*sizeof(char));
H.length=i;
    for(i=1;i<=H.length;i++)
H.ch[i]=sh[i-1];
return 0;
}
int Next(SString S,int * next){
int i=1,j=0;
next[1]=0;
while(i<=S.length)
{
if(j==0||S.ch[i]==S.ch[j]){i++;j++;next[i]=j;}
else j=next[j];
}
return 0;
}
int KMP(int *next,SString S,SString H){
int j=1,i=1;
while(i<=S.length&&j<=H.length){
if(S.ch[i]==H.ch[j]){i++;j++;}
else{ 
if(!next[j]) i++;
else j=next[j];
}
}
if(j>H.length) cout<<"success";
else cout<<"fail";
return 0;
}
int main(){
SString H,S;
char*a="beijing";
Ass(H,a);
int i=1;
while(i<=H.length)
{cout<<H.ch[i];i++;}
cout<<endl;
char*b="jing";
Ass(S,b);
i=1;
while(i<=S.length)
{cout<<S.ch[i];i++;}
cout<<endl;
int *next;
next=(int*)malloc((S.length+1)*sizeof(int));
Next(S,next);
KMP(next,H,S);
cout<<endl;
return 0;

}



0 0
原创粉丝点击