现在的位置: 首页 > 综合 > 正文

KMP算法实现

2017年12月06日 ⁄ 综合 ⁄ 共 493字 ⁄ 字号 评论关闭

KMP其实到现在还是很容易忘记(经常刚才懂,马上又忘了这么算出next值了),但是这个很不经常用,所以也没深究了

//KMP
#include <stdio.h>
main()
{
	char str1[100],str2[100];
	int n,m,q,i,j,p[100]={0};
    scanf("%d%d%*c",&n,&m);
	for(i=1;i<=n;i++)scanf("%c",&str1[i]);
	getchar();
	for(i=1;i<=m;i++)scanf("%c",&str2[i]);
	for(i=2;i<=m;i++)
	{
		q=i-1;
		while(str2[p[q]+1]!=str2[i]&&q!=0)
		q=p[q];
		if(str2[p[q]+1]==str2[i])p[i]=p[q]+1;
		else p[i]=0;
	}
	i=0;j=0;
	while(j<m&&i<=n)
	{
		if(str1[i+1]==str2[j+1])
		{
			i++;j++;
		}
  		else
		if(j==0)i++;
   		else j=p[j]; 
	}
	if(i<=n)printf("%d\n",i);
	else printf("no exist\n");
}

抱歉!评论已关闭.