Problem Description
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
思路
题目大概意思就问给定的字符串是否是EAEBE形式,首先利用kmp的next数组找到最长公共前后缀,那么前缀是[0,next[slen]],后缀是[slen - next[slen],slen]。在从最大的公共前后缀长度开始枚举进行单模匹配,单模匹配的范围[ next[slen],slen-next[slen] )。如果找不到公共前后缀的长度减小1,一旦找到就是最长输出即可。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
using namespace std;
const int maxn = 1e6+5;
char s[maxn],p[maxn];
int t[maxn];
void get_next(int n)
{
memset(t,-1,sizeof(t));
int i = 0,j = -1;
while(i < n){
if(j == -1 || s[i] == s[j]){
i++;j++;
t[i] = j;
}
else{
j = t[j];
}
}
}
int main()
{
int n;
scanf("%d",&n);
while(n--){
scanf("%s",s);
int slen = strlen(s);
get_next(slen);
int cnt = t[slen],ans = 0;
while(cnt){
memcpy(p,s,sizeof(char)*cnt);
p[cnt] = '\0';
get_next(cnt);
int i = cnt,j = 0;
while(i < slen-cnt && j < cnt){
if(j == -1 || s[i] == p[j]){
i++;j++;
}
else{
j = t[j];
}
}
if(j == cnt){ //找到即是最大退出即可
ans = cnt;
break;
}
cnt--; //缩小前后缀长度
}
printf("%d\n",ans);
}
return 0;
}
愿你走出半生,归来仍是少年~