Power Strings
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 50744 | Accepted: 21173 |
Description
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
Hint
This problem has huge input, use scanf instead of cin to avoid time limit exceed.
/*
题意: 给出一个字符串s,求重复子串出现的最大次数
分析:kmp的next[]数组的应用
要求重复子串出现的最大次数,其实就是要求字符串的最小循环节
这里我们假设这个字符串的长度是len,那么如果len可以被len-next[len]整除的话,我们就可以说
len-next[len]就是那个最短子串的长度
为什么呢? 假设我们有一个字符串 ababab 那么next[6]=4, 由于next的性质,匹配失配后,下一个能继续进行匹配的位置,
也就是说,把字符串的前四个字母,abab,平移2个单位,这个abab一定与原串的abab重合(否则就不满足失败函数的性质),zhejiu shuomi
题目分析转载于:http://bbezxcy.iteye.com/blog/1377787
*/
#include<iostream>
#include<cstring>
#include<algorithm>
#include<stdio.h>
using namespace std;
const int maxn =1e6+10;
int next[maxn]; /// 串的next数组 (看这个串的相似度)
char s1[maxn];
void kmp_pre(char x[],int m,int next[])
{
int i,j;
j=next[0]=-1;
i=0;
while(i<m){
while(-1!=j&&x[i]!=x[j])j=next[j];
next[++i]=++j;
}
}
int main()
{
while(scanf("%s",s1)!=EOF)
{
memset(next,0,sizeof(next));
if(s1[0]=='.')break;
int len=strlen(s1);
kmp_pre(s1,len,next);
int temp=len-next[len];
if(len%temp==0)printf("%d\n",len/temp);
else printf("1\n");
}
return 0;
}