poj 2406 Power Strings(KMP)
题目链接:http://poj.org/problem?id=2406
思路分析:
1.理解Kmp算法的next数组的意义;
2.对于字符A[i],i-next[i]等价于在字符串中存在一个长度为i-next[i]的重复子串;
3.当 i % (i - next[i]) == 0 等价于字符串由 (i/(i-next[i])) 个长度为 i - next[i]的子串连接组成;
代码:
#include <iostream> #include <string> using namespace std; const int MAX_N = 1000000 + 10; char S[MAX_N]; int Next[MAX_N]; int GetNext(char P[], int next[]) { int i = 0, j = -1; int len = strlen(P); if (len <= 0) return 0; next[0] = -1; while (i <= len) { if (j == -1 || P[i] == P[j]) next[++i] = ++j; else j = next[j]; } } int main() { int len; int lenSubstr; while (scanf("%s", S) != EOF && strcmp(S, ".")) { len = strlen(S); GetNext(S, Next); lenSubstr = len - Next[len]; if (len % lenSubstr == 0) printf("%d\n", len / lenSubstr); else printf("1\n"); } return 0; }