题意:
给定一个EAEBE的字符串,|L|<=106,求最长的E
分析:
nxt[n]是前缀和后缀的lcp,也就是第一个E和最后一个E
但是中间不一定能找到,所以要扫一下这个nxt数组去kmp匹配
aaaabbbbbbaaaaaa这种数据就要O(n2)了,数据随机所以我也过了
网上还有另一种标记nxt数组的长度的是O(n)的
exkmp讨论的神做法: exkmp做法
代码:
//
// Created by TaoSama on 2015-11-03
// Copyright (c) 2015 TaoSama. All rights reserved.
//
//#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>
using namespace std;
#define pr(x) cout << #x << " = " << x << " "
#define prln(x) cout << #x << " = " << x << endl
const int N = 1e6 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7;
int n, nxt[N];
char s[N];
void getNxt(char *t, int m) {
nxt[0] = -1;
int i = 0, j = -1;
while(i < m) {
if(j == -1 || t[i] == t[j]) nxt[++i] = ++j;
else j = nxt[j];
}
}
bool kmp(char *s, char *t, int n, int m) {
int i = 0, j = 0;
while(i < n) {
if(j == -1 || s[i] == t[j]) ++i, ++j;
else j = nxt[j];
if(j == m) return true;
}
return false;
}
int main() {
#ifdef LOCAL
freopen("C:\\Users\\TaoSama\\Desktop\\in.txt", "r", stdin);
// freopen("C:\\Users\\TaoSama\\Desktop\\out.txt","w",stdout);
#endif
ios_base::sync_with_stdio(0);
int T; scanf("%d", &T);
while(T--) {
scanf("%s", s);
n = strlen(s);
getNxt(s, n);
int ans = nxt[n];
while(ans && (ans > n / 3 || !kmp(s + ans, s, n - 2 * ans, ans)))
ans = nxt[ans];
printf("%d\n", ans);
}
return 0;
}