Given two strings a and b we define ab to be their concatenation. For example, if a = “abc” and b = “def” then ab = “abcdef”. If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = “” (the empty string) and a^(n+1) = a*(a^n).
Input
Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.
Output
For each s you should print the largest n such that s = a^n for some string a.
Sample Input
abcd
aaaa
ababab
.
Sample Output
1
4
3
给一个字符串,找到循环节的数目。
前缀"指除了最后一个字符以外,一个字符串的全部头部组合;
"后缀"指除了第一个字符以外,一个字符串的全部尾部组合。
这里举个例子:
这样我们就求出来了next数组
我们求next[3]的时候,已经求出next[0]~next[2],此时我们知道了next[2]=1,意味着next[2]是代表着字符串的前缀与后缀相同的最大长度为1。
也就是对于ABA来说,前缀与后缀相同的最大长度为1,这是我们已知的条件,现在我们要知道对于ABAB来说,前缀与后缀相同的最大长度为??????
对于ABA来说,前缀"AB",后缀"BA",对于ABAB来说,前缀“ABA”,后缀“BAB”,现在我们观察得出结论
ABAB的前缀和后缀必然分别包含ABA的前缀和后缀,即next[3]字符串的前缀和后缀必然分别包含next[2]的前缀和后缀,
无论该字符串是何值。
既然我们已经知道了next[2]=1,代表着ABA的前缀与后缀相同的最大长度为1,那我们计算next[3]的时候,就知道了第一个字符必然是相同的,所以我们无需再比较第一个字符了,(KMP算法就是为了省这一步!!!!),所以我们将t[3]直接与t[1]而不是t[0]比较,若t[3]=t[1],那我们可以直接说next[3]=2=next[1]+1.
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
long long l,nx[1000000];
void wsx(char s[])
{
int i=0,j=-1;
nx[0]=-1;
while(i<l)
{
if(j==-1||s[i]==s[j])
{
i++;
j++;
nx[i]=j;
}
else
j=nx[j];
}
}
char ss[1001000];
int main()
{
while(~scanf("%s",ss))
{
if(ss[0]=='.')
break;
l=strlen(ss);
wsx(ss);
int t=l-nx[l];
if(l%t==0)如果第i-1位为结尾的循环必定有 i % (i - Next[i]) == 0
printf("%d\n",l/t);
else
printf("1\n");
}
return 0;
}