题目描述:
abcd aaaa ababab .Sample Output
1 4 3
题目大意:给一个字符串,求最短的循环节的长度.
题目分析:使用kmp算法求出next数组,length-1-next[length-1]即为最短循环节的长度.
AC代码如下:
# include<iostream>
# include<cstdio>
# include<cstring>
# include<algorithm>
using namespace std;
const int N=1000000;
int nxt[N+5];
char s[N+5];
void getNext(char *s)
{
int n=strlen(s);
nxt[0]=nxt[1]=0;
for(int i=1;i<n;++i){
int j=nxt[i];
while(j&&s[i]!=s[j]) j=nxt[j];
nxt[i+1]=(s[i]==s[j])?j+1:0;
}
}
bool check(int x)
{
int n=strlen(s);
for(int i=0;i+x<n;i+=x){
int j=i+x,k=i;
while(k<i+x){
if(s[k]!=s[j]) return false;
++j,++k;
}
}
return true;
}
void solve()
{
int n=strlen(s);
if(n==1) printf("1\n");
else{
int x=n-1-nxt[n-1];
if(n%x) printf("1\n");
else{
if(check(x)) printf("%d\n",n/x);
else printf("1\n");
}
}
}
int main()
{
//freopen("in.txt","r",stdin);
while(~scanf("%s",s)&&!strchr(s,‘.‘))
{
getNext(s);
solve();
}
return 0;
}
原文:http://www.cnblogs.com/20143605--pcx/p/6293462.html