经典KMP算法

#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));
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值