Problem
It's time for music! A lot of popular musicians are invited to join us in the music festival. Each of them will play one of their representative songs. To make the programs more interesting and challenging, the hosts are going to add some constraints to the rhythm of the songs, i.e., each song is required to have a 'theme section'. The theme section shall be played at the beginning, the middle, and the end of each song. More specifically, given a theme section E, the song will be in the format of 'EAEBE', where section A and section B could have arbitrary number of notes. Note that there are 26 types of notes, denoted by lower case letters 'a' - 'z'.
To get well prepared for the festival, the hosts want to know the maximum possible length of the theme section of each song. Can you help us?
Input
The integer N in the first line denotes the total number of songs in the festival. Each of the following N lines consists of one string, indicating the notes of the i-th (1 <= i <= N) song. The length of the string will not exceed 10^6.
Output
There will be N lines in the output, where the i-th line denotes the maximum possible length of the theme section of the i-th song.
Sample Input
5
xy
abc
aaa
aaaaba
aaxoaaaaa
Sample Output
0
0
1
1
2
思路
題意是給定字符串碌识,找出最長的子串長度,該子串需滿足:在串的開頭瞭稼、中間和結(jié)尾分別出現(xiàn)一次踩衩,且不能交叉恍涂。
思路為KMP變形。先用字符串生成失配數(shù)組。設文本串長度為len弃鸦。串從0開始編號听盖。我們考慮匹配第len個位置胀溺。失配數(shù)組每跳一個位置。都能保證文本串的開頭位置匹配皆看。所以只需在剩下的中間部分找有沒有匹配的子串仓坞。如果有說明滿足條件。
代碼
#include <cstdio>
#include <cstring>
using namespace std;
const int M=1e6+5;
int f[M];
char str[M];
void getnext(char *p){
int n=strlen(p);
f[0]=f[1]=0;
for(int i=1;i<n;i++){
int j=f[i];
while(j&&p[j]!=p[i])j=f[j];
f[i+1]=p[j]==p[i]?j+1:0;
}
}
bool kmp(char *T,char *p,int n,int m){
for(int i=0,j=0;i<n;i++){
while(j&&p[j]!=T[i])j=f[j];
if(p[j]==T[i])j++;
if(j==m)return true;
}
return false;
}
int main(){
int t,j,res,len;
scanf("%d",&t);
while(t--){
res=0;
scanf("%s",str);
len=strlen(str);
getnext(str);
j=f[len];
while(j){
if(len>=3*j&&kmp(str+j,str,len-2*j,j)){res=j;break;}
j=f[j];
}
printf("%d\n",res);
}
return 0;
}