KMP算法 KMP模式匹配 一(串)

A - KMP模式匹配 一(串)
Crawling in process... Crawling failed Time Limit:1000MS     Memory Limit:131072KB     64bit IO Format:%lld & %llu

Description

求子串的next值,用next数组存放,所有输出

Input

输入一个字符串

Output

输出全部next值

Sample Input

abaabcac

Sample Output

0 1 1 2 2 3 1 2


#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int next[10005];
char str[10005];
int len;
void getnext(char *str,int next[])
{
    int j,k;
	next[1]=0;
	j=1;
	k=0;
	while(j<=len)
		if((k==0)||(str[j]==str[k]))
		{
			++j;
			++k;
			next[j]=k;
		}
		else
			k=next[k];
}

int main()
{
	char s[1005];
	cin>>s;
	len =strlen(s);
	int j,k;
	for(j=1,k=0;k<len;j++,k++)
	{
		str[j]=s[k];
	}
	int i;
	getnext(str,next);
	for(i=1;i<len;i++)
        cout<<next[i]<<" ";
	cout<<next[len]<<endl;
	return 0;
}




posted @ 2014-08-01 18:57  mengfanrong  阅读(228)  评论(0编辑  收藏  举报