poj 2406 Power Strings ( KMP求循环节 )
题目含义:
给定一个字符串,问该字符串最多是由它的一个字串复制几次而成的
思路:
KMP的next数组求循环节,求出最小的循环节,如果字符串长度是循环节的整数倍,说明该字符串复制 len / next[len]次后即可得到,如果有余数,说明不能得到,只能由自身自我复制一次得到
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1e6 + 10;
int nex[N];
char s[N];
void get_next(char* p){
int len = strlen(p);
nex[0] = -1;
int i = 0, k = -1;
while (i < len){
if(k == -1 || p[i] == p[k]){
++i, ++k;
nex[i] = k;
}
else k = nex[k];
}
}
int main()
{
while (~scanf("%s", s) && s[0] != '.'){
memset(nex, 0, sizeof nex);
int len = strlen(s);
get_next(s);
int res = len - nex[len];
if(len % res)puts("1");//不能省略
else printf("%d\n", len / res);
}
return 0;
}
本文来自博客园,作者:correct,转载请注明原文链接:https://www.cnblogs.com/correct/p/12862041.html

浙公网安备 33010602011771号