KMP算法模板

推荐两篇博客:传送门1

                         传送门2

先上大学学的KMP吧,下面那个是高中时候学的:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char s[1005],t[1005];
int next[1005],n,m;
void makenext()
{
	int i=0,j=-1;
	next[i]=j;
	while(i<m)
	{
		if(j==-1||t[i]==t[j])
		{
			i++;
			j++;
			next[i]=j;
		}
		else j=next[j];
	}
	return;
}
int makeKmp()
{
	int i=0,j=0;
	while(j<m&&i<n)
	{
		if(s[i]==t[j]||j==-1)
		{
			i++;
			j++;
		}
		else
		{
			j=next[j];
		}
	}
	if(j==m)return i-j;
	else return -1;
}
int main()
{
	scanf("%s",s);
	scanf("%s",t);
	n=strlen(s);
	m=strlen(t);
	makenext();
//	for(int i=0;i<m;i++)cout<<next[i]<<" ";
//	cout<<endl;
    if(makeKmp()!=-1)
	cout<<"字符串t在s中的位置为"<<makeKmp()+1;
    else cout<<"字符串t在s中不存在";
	return 0;
}

next数组的生成:

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
#include<algorithm>
using namespace std;

void makeNext(const char P[],int next[])
{
    int q,k;//q:模版字符串下标;k:最大前后缀长度
    int m = strlen(P);//模版字符串长度
    next[0] = 0;//模版字符串的第一个字符的最大前后缀长度为0
    for (q = 1,k = 0; q < m; ++q)//for循环,从第二个字符开始,依次计算每一个字符对应的next值
    {
        while(k > 0 && P[q] != P[k])//递归的求出P[0]···P[q]的最大的相同的前后缀长度k
            k = next[k-1];          //不理解没关系看下面的分析,这个while循环是整段代码的精髓所在,确实不好理解  
        if (P[q] == P[k])//如果相等,那么最大相同前后缀长度加1
        {
            k++;
        }
        next[q] = k;
    }
}
int main()
{
	int next[100001]={0};
	char T[100001];
	char P[100001];
	int i;
	cin.getline(P,100001);
	makenext(P,next);
		int max=0;
	for(int i=1;i<=10;i++)
	{
		if(next[i]=1)
	     cout<<next[i];
	     else
	     cout<<"no";
	}
      
	return 0;
	
}

 

代码模板:

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char p[1001],t[1001];
int next[1001]={0};
void makenext(char p[],int next[])//不理解就自己代一代 
{
	int m=strlen(p),k,q;
	next[0]=0;
	for(k=0,q=1;q<m;q++)
	{
		while(k>0&&p[k]!=p[q])k=next[k-1];
		if(p[k]==p[q])k++;//查找与前面有相同的,即前后缀有相同的元素,于是就加1
		next[q]=k;
	}
}

void KMP(char p[],char t[],int next[])
{
	int n=strlen(t);
	int m=strlen(p);
	int q,i;
	makenext(p,next);
	for(q=0,i=0;i<n;i++)
	{
		while(q>0&&p[q]!=t[i])q=next[q-1];
		if(p[q]==t[i])q++;
		if(q==m)
		{
			printf("%d\n",i-m+2);
		}
	}
}

int main()
{
	gets(t);
	gets(p);
	KMP(p,t,next);
	return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值