A - KMP模式匹配 一(串)


Time Limit:1000MS     Memory Limit:131072KB     64bit IO Format:%lld & %llu


Submit  Status



Description



求子串的next值,用next数组存放,全部输出



Input



输入一个字符串



Output



输出所有next值



Sample Input



abaabcac





Sample Output



0 1 1 2 2 3 1 2





代码:


#include <iostream>
#include <cstring>
using namespace std;
int len;
void getnext(char str[],int next[])
{
   int i,j;
   i=1;j=0;
   next[1]=0;
   while(i<=len)
   {
	   if(j==0||str[i]==str[j])
	   {
		   ++i;++j;
		   next[i]=j;
	   }
	   else
		   j=next[j];
   }
}
int main()
{
	char str[10000];
	int next[10000];
	int i,j;
	cin>>str;
	len=strlen(str);
	for(j=len;j>0;j--)
		str[j]=str[j-1];
	getnext(str,next);
	for(i=1;i<=len;i++)
	{
		cout<<next[i];
		if(i<len)
			cout<<' ';
	}
	cout<<endl;
	return 0;
}