利用kmp求next数组的思想对字符串进行模式匹配。
显而易见,最后一个字符的匹配到的位置到最后一个字符是一个循环节。
例如
匹配串: a b a c a b a c
next数组:0 1 1 2 1 2 3 4
第8个字符的next数组的值为4;
则一个循环节为8-4+1=4;
总共的循环次数为8/4=2次;
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
char str[1100000];
int next[1100000];
void chu()
{
int i=0,j=-1;
next[i]=j;
int len=strlen(str);
while(i<len)
{
if(j==-1||str[i]==str[j])
{
i++;j++;
next[i]=j;
}
else j=next[j];
}
int k=len-j;
if(len%k==0)
{
cout<<len/k<<endl;
}
else cout<<1<<endl;
}
int main()
{
while(~scanf("%s",str))
{
if(str[0]=='.')break;
chu();
}
return 0;
}