poj2406
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
利用又见kmp中的法一求出失配函数,即求出以每个字符做结尾的后缀时所对应的前面的以某字符做结尾前缀的那个字符在哪,不用求next数组,因为不涉及匹配后再重新找位置
如果最后一个字符和他的f(i)的距离能被字符串长度整除,说明有重复循环节,且循环次数就是长度除以最后一个字符和他的f(i)的距离
总结:只对模式串操作时只用求失配函数(更加形象便于理解)
#include<stdio.h>
#include<iostream>
using namespace std;
int next[1000001];
void getNext(string s)
{
int i,j;
next[0]=-1;
for(i=1;i<s.size();i++)
{
for(j=next[i-1];;j=next[j])
{
if(s[j+1]==s[i])
{
next[i]=j+1;
break;
}
else if(j==-1)
{
next[i]=-1;
break;
}
}
}
}
int main()
{
string s;
while(cin>>s)
{
if(!s.compare("."))
break;
getNext(s);
int j=next[s.size()-1],sum=1;
while(j!=-1){
j=next[j];
sum++;
}
if(next[s.size()-1]!=-1&&sum*(s.size()-1-next[s.size()-1])==s.size())
cout<<sum<<endl;
else
cout<<1<<endl;
}
}