poj2406 Power Strings
很简单的KMP变形,求字符串中循环节个数。
完整代码如下
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
char s[1000005];
int next[1000005];
int main(){
while(1){
scanf("%s",s);
if(s[0] == '.')break;
int len = strlen(s);
int i = 0,j = -1;
next[0] = -1;
while(i != len){
if(j == -1 || s[i] == s[j])
next[++i] = ++j;
else j = next[j];
}
int ans = 1;
if(len % (len - next[len]) == 0){
ans = len / (len - next[len]);
}
printf("%d\n",ans);
}
return 0;
}
本文介绍了一道经典的KMP算法变形题目——POJ2406 PowerStrings,通过实例讲解了如何利用KMP算法来确定字符串中的循环节个数,并提供了完整的C++代码实现。
613

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



