标签:
分析:对next数组的深入理解,最重要的还是对最小循环节的处理。
#include <stdio.h>
#include <string.h>
int next[100005];
char str2[100005];
void build_next(int len2)
{
int i=0,j=-1;
next[0] = -1;
while (i < len2)
{
if (j==-1 || str2[i] == str2[j])
{
i++;
j++;
// if (str2[i] != str2[j])
// {
next[i] = j;
// }
// else
// next[i] = next[j];
}
else
j = next[j];
}
}
// int KMP(int len1,int len2)
// {
// build_next(len2);
// int i=0,j=0,cnt=0;
//
// while (i < len1)
// {
// if (j==-1 || str1[i] == str2[j])
// {
// i++;
// j++;
// }
// else
// j = next[j];
// }
// return j;
// }
int main()
{
int N,n,i;
while (~scanf("%d%*c",&N))
{
while (N--)
{
gets(str2);
int len=strlen(str2);
build_next(len);
// for (i=0;i<=len;i++)
// {
// printf("%d",next[i]); //测试专用
// }
// printf("\n");
int length=len-next[len]; // 循环节的长度
// printf("%d",next[len]);
if (length!=len && len%length==0)
{
printf("0\n");
}
else
printf("%d\n",length-next[len]%length); //取余的作用:比如abcabcab next[len]=5,length=3,所以取余作用为去掉abc留下ab
}
}
return 0;
}
3 aaa abca abcde
0 2 5
HDU 3746 Cyclic Nacklace (KMP 循环节)
标签:
原文地址:http://blog.csdn.net/xinwen1995/article/details/46285941