POJ2406A- Power Strings
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.
思路:题意是让你求能构成循环的最多次数,关键是利用next数组的构建,其是KMP算法的精髓。
对于代码中i-next[i]代表了字符串最小前缀且满足能不但的复制得到
原字符串;len%(i-next[i])==0时代表字符串刚刚是子串的整数倍;
若len%(i-next[i])==0匹配时每一次移动的距离i-next[i]是相等的,若不等则只有最后一次不等;
#include <iostream>
#include<cstring>
#include<cstdio>
using namespace std;
char str[1000010],pat[1000010];//pat为模式串,str为主串
int Next[1000010]; //Next[x]下标x表示匹配失败处字符下标
//模式串pat的前缀与x位置的后缀的最大匹配字符个数-1
void GetNext(char *pat)
{
int LenPat = strlen(pat);
int i = 0,j = -1;
Next[0] = -1;
while(i < LenPat)
{
if(j == -1 || pat[i] == pat[j])
{
i++,j++;
Next[i] = j;
}
else
j = Next[j];
}
}
/*
int KMP()//返回模式串pat在str中第一次出现的位置
{
int LenStr = strlen(str);
int LenPat = strlen(pat);
//GetNext(pat);
int i = 0,j = 0;
int ans = 0;//计算模式串在主串匹配次数
while(i < LenStr)
{
if(j == -1 || str[i] == pat[j])
i++,j++;
else
j = Next[j];
if(j == LenPat)
{
//ans++; ans存放匹配次数,去掉return,最后返回ans
return i - LenPat + 1;
}
}
return -1;//没找到匹配位置
//return ans;//返回匹配次数。
} */
int main()
{
while(scanf("%s",str))
{
if(str[0]=='.')
break;
int len=strlen(str);
GetNext(str);
int k=len-Next[len];
int ans;
if(len%k==0)
ans=len/k;
else
ans=1;
printf("%d\n",ans);
}
return 0;
}