//4_7_18: Period 求字符串的所有前缀周期 POJ1961 ZOJ2177
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxc = 1000000 + 10;
int len;
int suf[maxc];
char str[maxc];
void KMP()
{
len = strlen(str);
int j = 0,k = -1;
suf[0] = -1;
while(j < len)
{
if(k == -1 || str[j] == str[k])
{
j ++;
k ++;
suf[j] = k;
if(k != 0 && j % (j - suf[j]) == 0)
printf("%d %d\n",j,j / (j - suf[j]));
}
else k = suf[k];
}
}
int main()
{
int i = 1,N;
while(scanf("%d",&N), N != 0)
{
scanf("%s",str);
printf("Test case #%d\n",i++);
KMP();
printf("\n");
}
return 0;
}
/*测试结果:通过POJ1961 ZOJ2177检测
3
aaa
Test case #1
2 2
3 3
12
aabaabaabaab
Test case #2
2 2
6 2
9 3
12 4
4
abcd
Test case #3
0
请按任意键继续. . .
*/POJ1961 ZOJ2177 Period
最新推荐文章于 2021-02-17 13:26:15 发布
本文介绍了一种使用KMP算法求解字符串所有前缀周期的方法,并提供了完整的C++实现代码。通过具体示例展示了如何运行该算法并输出结果。
682

被折叠的 条评论
为什么被折叠?



