解题思路:
只需要判断中间是否存在和前缀后缀相等的字符串即可。
#include <iostream> #include <cstring> #include <cstdlib> #include <cstdio> #include <algorithm> #include <vector> #include <cmath> #include <queue> #include <set> using namespace std; const int maxn = 1000000 + 10; char s[maxn]; int next[maxn]; void get_next() { int m = strlen(s); next[0] = 0; next[1] = 0; for(int i=1;i<m;i++) { int j = next[i]; while(j && s[i] != s[j]) j = next[j]; next[i+1] = (s[i] == s[j]) ? j + 1 : 0; } } bool KMP(char *p, char *t, int n, int m) { int i , j; for(i=0,j=0;i<n;i++) { while(j && t[j] != p[i]) j = next[j]; if(t[j] == p[i]) j++; if(j == m) return 1; } return 0; } int main() { int T; scanf("%d", &T); while(T--) { scanf("%s", s); get_next(); int n = strlen(s); int j = next[n]; int ans = 0; while(j) { if(n >= 3 * j && KMP(s+j,s,n-2*j,j)) { ans = j; break; } j = next[j]; } printf("%d\n", ans); } return 0; }
原文:http://blog.csdn.net/moguxiaozhe/article/details/43451705