新浪博客 发表时间 -- 2009-07-28 21:19:38
Power Strings
这道题题目意思很明显,要让我们求最长重复字符串,刚好,老师讲了KMP算法,想想也应该是用KMP算法来解决,但也找不到好的解决办法...
上网查了下,发现了别人的一个思想,就是题目要找最长重复字符串,我们先用字符串长度减去找到的位置,然后用字符串长度来判断是否能整除于它,行的话结果就等于字符串长度除于它,否则就赋值为1...
代码:
#include "iostream"
#include "string.h"
using namespace std;
int Getnextval(char str[],int nextval[])
{
int j=0,k=-1,d;
d=strlen(str);
nextval[0]=-1;
while (j<d)
{
if (k==-1||str[j]==str[k])
{
j++;
k++;
if (str[j]!=str[k])
{
nextval[j]=k;
}
else
nextval[j]=nextval[k];
}
else
k=nextval[k];
}
j-=k;
return j;
}
int main()
{
char str[1000001];
int a[1000000],d,h,i,max;
while (1)
{
gets(str);
if (str[0]=='.'&&str[1]=='\0')
{
break;
}
d=strlen(str);
h=Getnextval(str,a);
if (d%h==0)
{
h=d/h;
}
else
h=1;
printf("%d\n",h);
}
return 0;
}