Top

HDU - 4763 -Theme Section(迭代求公共前后缀跑KMP)


博主链接

题目链接

题意:

给一个字符串,求出字符串的最大的相同前缀后缀,并且满足前缀后缀在字符串中间出现了。

题解:

可以先对字符串跑KMP求一下Next数组,由next数组定义可以知道,里面存的是当前字符最长前缀和后缀,所以我们只需要从最后一个字符出发,递归寻找每个长度为的Next值的前缀后缀,对于长度为len的前缀,只需要用该前缀起和字符串的除了前缀和后缀的部分匹配就可以了,如果匹配成功,就看是否需要更新答案。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include<stdio.h>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1e6+21;
const int mod=1e9+7;
char s[maxn];
int nex[maxn];
int len;
void GetNex(){
int j=-1;
for(int i=0;s[i];i++){
while(s[i]!=s[j+1]&&j!=-1)j=nex[j];
if(s[i]==s[j+1]&&i!=0)j++;
nex[i]=j;
}
}
bool kmp(int l){
int j=-1;
for(int i=l;i<len-l;i++){
while(j!=-1&&s[j+1]!=s[i])j=nex[j];
if(s[i]==s[j+1])j++;
if(j+1==l)return true;
}
return false;
}
int main(){
int t;
scanf("%d",&t);
while(t--){
scanf("%s",s);
len=strlen(s);
if(len<3){
puts("0");
continue;
}
GetNex();
int ans=nex[len-1];
int mx=0;
while(ans!=-1){
if(kmp(ans+1)){
mx=max(mx,ans+1); //查找中间是否有这个串
}
ans=nex[ans];
}
printf("%d\n",mx);
}
return 0;
}


未经允许不得转载: Anoyer's Blog » HDU - 4763 -Theme Section(迭代求公共前后缀跑KMP)