poj 2406
Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def" then a*b = "abcdef". If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = "" (the empty string) and a^(n+1) = a*(a^n).
Input
Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.
Output
For each s you should print the largest n such that s = a^n for some string a.
Sample Input
abcd aaaa ababab .Sample Output
1 4 3
题目大意 :
此题就可以借助 kmp 的 next数组,因为 next 数组所表示的意义就是当前位置前面的串的最长公共前后缀,所以最后一位中的 next 所存的值就表示其前面的前缀的最长公共部分 是多少 ,用总的长度减去前缀的长度 ,就得出了最小回文的串的长度。
代码示例 :
/*
* Author: ry
* Created Time: 2017/10/5 7:29:46
* File Name: 1.cpp
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <time.h>
#include <map>
using namespace std;
const int eps = 1e6+5;
#define ll long long
char s[eps];
int next[eps];
int len;
void getnext(){
int i = 0, j = -1;
next[0] = -1;
while (i != len){
if (j == -1 || s[i] == s[j]){
i++;
j++;
next[i] = j;
}
else j = next[j];
}
}
int main() {
while (gets(s) != NULL){
if (s[0] == '.') break;
len = strlen(s);
getnext();
int ff = len - next[len];
if ((len - ff) % ff == 0) printf("%d\n", len/ff);
else printf("1\n");
}
return 0;
}
/*
sadjkghrfkjashioawruiofhasjklryqwodhasnkbfgakjsrhoqwuiyeaskjbtrjksa
*/