#include<stdio.h>
#include<string.h>
//串的定长顺序存储
#define MAXLEN 1000000 //串的最大长度
typedef struct{
char ch[MAXLEN+1]; //存储串的一维数组
int length; //串的当前长度
}SString;
int i,j;
int next[1000000];
//next函数
void get_next(SString T,int next[])
{
//求模式串T的next函数值并存入数组next
i=1;
next[1]=0;
j=0;
while(i<T.length)
{
if(j==0||T.ch[i]==T.ch[j]){
++i;
++j;
next[i]=j;
}
else{
j=next[j];
}
}
}
//KMP算法
int Index_KMP(SString S,SString T,int pos)
{
//利用模式串T的next函数求T在主串S中第pos个字符之后的位置
//其中,T非空,1<=pos<=S.length
i=pos;j=1;
while(i<S.length && j<=T.length) //两个串均未比较到串尾
{
if(j==0||S.ch[i]==T.ch[j]){ //继续比较后继字符
++i;
++j;
}
else{ //模式串向右移动
j=next[j];
}
}
if(j>T.length){ //匹配成功
return i-T.length;
}
else{ //匹配失败
return -1;
}
}
//BF算法
int Index_BF(SString S,SString T,int pos)
{
//返回模式T在主串S中第pos个字符开始第一次出现的位置。若不存在,则返回值为0
//其中,T非空,1<=pos<=S.length
i=pos;j=1; //初始化
while(i<S.length && j<=T.length) //两个串均未比较到串尾
{
if(S.ch[i]==T.ch[j]){ //继续比较后继字符
++i;
++j;
}
else{ //指针后退重新开始匹配
i=i-j+2;
j=1;
}
}
if(j>T.length){ //匹配成功
return i-T.length;
}
else{ //匹配失败
return -1;
}
}
//主函数
int main()
{
SString str1,str2;
char p1[1000000],p2[1000000];
scanf("%s%s",p1,p2);
strcpy(p1,str1.ch);
strcpy(p2,str2.ch);
int next[1000000];
get_next(str2,next);
//printf("%d\n",Index_KMP(str1,str2,1));
//printf("%d\n",Index_BF(str1,str2,1));
}
经典KMP算法
最新推荐文章于 2024-05-17 18:31:56 发布