KMP算法学习笔记

KMP是一种字符串匹配算法,网上有许多的讲解和介绍,都非常清楚明白,这里只说明一点next[i]表示[1,i-1]位中的最长公共前缀后缀,因此在遇到字符不匹配时,直接将字符串右移j-next[j]位即可。不多说了,直接上习题

POJ 3461 Oulipo KMP算法裸题,直接上模板 code:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char s1[10001],s2[1000001];
int next[10001];
int main()
{
	int l1,l2,n,i,j,ans;
	scanf("%d",&n);
	while (n--)
	  {
	    scanf("%s%s",&s1,&s2);
	    i=0; j=-1;
	    memset(next,0,sizeof(next));
	    next[0]=-1;
	    l1=strlen(s1); l2=strlen(s2);
	    while (i<l1)
	      {
	        if (j==-1||s1[i]==s1[j])
	          {
	            ++i; ++j;
	            next[i]=j;
	          }
	        else
	          j=next[j];
	      }
	    i=0; j=0; ans=0;
	    while (i<l1&&j<l2)
	      {
	        if (s1[i]==s2[j]||i==-1)
	          {
	            i++;
	            j++;
	          }
	        else
	          i=next[i];
	        if (i==l1)
	          {i=next[i]; ans++;}
	      }
	    printf("%d\n",ans);
	  }
}
POJ 2752 Seek the Name,Seek the Fame 在理解了next数组的实质之后,这题可以类似与递归的求解(PS:最长公共前缀的后缀必定为最长公共后缀的后缀)code:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char s[400001];
int next[400001],res[400001];
int main()
{
	int i,l,j,t;
	while (gets(s))
	  {
	    l=strlen(s);
	    memset(next,0,sizeof(next));
		i=0; j=-1; next[0]=-1;
		while (i<l)
		  {
		    if (j==-1||s[i]==s[j])
			  {
			    i++;
			    j++;
			    next[i]=j;
			  }      
			else
			  j=next[j];
		  }
		memset(res,0,sizeof(res));
		j=l; t=0;
		while (j>0)
		  {
		  	res[++t]=j;
		    j=next[j];	
		  }
		for (i=t;i>=1;--i)
		  printf("%d ",res[i]);
		printf("\n");
	  }
}
POJ 2406 Power Strings 与上一题思路基本一致,只不过至此寻找的是循环节,如果l%(l-next[l])就是循环字符串,循环个数为l/(l-next[l]) code:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char s[1000001];
int next[1000001];
int main()
{
	int i,j,l,ans;
	scanf("%s",&s);
	while (s[0]!='.')
	  {
	  	memset(next,0,sizeof(next));
	    l=strlen(s);
		i=0; j=-1; next[0]=-1;
		while (i<l)
		  {
		    if (j==-1||s[i]==s[j])
		      {
		        i++;
		        j++;
		        next[i]=j;
		      }
		    else
		      j=next[j];
		  }	
		l=i;
		cout<<next[l]<<endl;
		if (l%(l-next[l])) printf("1\n");
		else printf("%d\n",l/(l-next[l]));
		scanf("%s",&s);
	  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值