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.
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
char se[1100000];
int next[1100000];//next[i]表示前面长度为i的子串
void get(int m)
{
int i=1,j=0;
next[0]=0;
while(i<m)
{
if(se[i]==se[j])
next[i++]=++j;
else if(!j)
{
next[i]=0;
i++;
}
else
j=next[j-1];
}
}
int main()
{
while(~scanf("%s",se)&&se[0]!='.')//se[0]等于.时结束
{
int l1,l2;//l1为前缀和后缀相等的最大长度
l1=strlen(se);//测字符串得长度
get(l1);
l2=l1-next[l1-1];//最小循环节的长度
if(l1%l2==0)//判断一下字符串是不是由循环节组成的
printf("%d\n",l1/l2);
else
printf("1\n");
}
return 0;
}
题意 给定一个字符串m,求一个最短的子串n,m是n重复多次组成的
思路 kmp算法
kmp的next数组介绍
KMP的next数组告诉我们:当模式串中的某个字符跟主串中的某个字符失配时,模式串下一步应该跳到哪个位置。如模式串中在j 处的字符跟主串在i 处的字符匹配失配时,下一步用next [j] 处的字符继续跟主串i 处的字符匹配,相当于模式串向右移动 j - next[j] 位。