题目描述
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).
输入
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.
输出
For each s you should print the largest n such that s = a^n for some string a.
样例输入
abcd
aaaa
ababab
.
样例输出
1
4
3
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#define maxn 1000007
using namespace std;
int kmp[maxn];
int len;
void kmpf(char a[]) //获得除去最小字符串剩余字符串长度的函数
{
int i=0,j=-1;
kmp[0]=-1;
while(i<len)
{
if(j==-1||a[i]==a[j])
{
i++,j++;
kmp[i]=j; //记录位置,下次从这个地方开始进行比较,联系下面的else
}
else
{
j=kmp[j];
}
}
}
int main()
{
char b[maxn]; //存字符串
int length; //字符串长度
while(~scanf("%s",b))
{
if(b[0]=='.')break;
len=strlen(b);
kmpf(b);
length=len-kmp[len]; //最小字符串的长度
if(len%length==0)cout<<len/length<<endl; //如果整除,说明是最小字符串的幂
else cout<<1<<endl; //不整除,说明这个字符串没有所谓的规律性,便为1
}
return 0;
}
“从上次匹配失败的地方进行匹配,这样就减少了匹配次数,增加了效率。”–百度百科
那是百度百科对kmp算法的其中一个描述
所以才有kmp[i]=j;
这个j的位置对应上次跟i进行比较的地方
然后j=kmp[j]也就是从这个地方开始比较了
这样可以大大增加比较的效率