Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def" then a*b = "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
我的代码# include<stdio.h># include<string.h>
char ss[1000002];
int next[1000002],len;
void getNext()
{
int i=1,j=0;
next[1]=0;
while(i<len)
{
if(j==0||ss[i]==ss[j])
{
i++;j++;
next[i]=j;
}
else
j=next[j];
}
}
int main()
{
while(1)
{
int i,j,seg,sum=0;
scanf("%s",ss+1);
len=strlen(ss+1);
if(len==1&&ss[1]=='.')
break;
getNext();
seg=len-next[len];
for(i=seg;i<=len-seg;i+=seg)////拖沓。。。。
if(ss[i]!=ss[i+seg])
{
sum=1;
break;
}
if(len%seg==0&&sum==0)
printf("%d\n",len/seg);
else
printf("%d\n",1);
}
return 0;
}
、、大神的代码!!!!!
- #include<stdio.h>
- #include<string.h>
- #define max 1000000
- int next[max];
- char str1[max];
- int get_next(char *pat)
- {
- int j=0,k=-1;
- int len=strlen(pat);
- next[0]=-1;
- while(j<len)
- {
- if(k==-1||pat[j]==pat[k])
- next[++j]=++k;
- else
- k=next[k];
- }
- j=len-k;//如果最后一个位置不匹配,那么就会滚到len-k的位置,也就是最小重复字串的长度。
- if(len%j==0)
- return len/j;
- else
- return 1;
- }
- int main()
- {
- while(scanf("%s",&str1)!=EOF)
- {
- if(str1[0]=='.')
- break;
- printf("%d\n", get_next(str1));
- }
- return 0;
- }