HDU4763——Theme Section

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


思路

题意是给定字符串,找出最长的子串长度,该子串需满足:在串的开头、中间和结尾分别出现一次,且不能交叉。
思路为KMP变形。先用字符串生成失配数组。设文本串长度为len。串从0开始编号。我们考虑匹配第len个位置。失配数组每跳一个位置。都能保证文本串的开头位置匹配。所以只需在剩下的中间部分找有没有匹配的子串。如果有说明满足条件。

代码

#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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第一章:悲.喜 “你可以走,小宇必须给我留下” “不要,我和小宇不能分开,小宇必须要我带走” ……… “晴啊,别担...
    朴千晗阅读 575评论 0 0
  • 孰能生巧 写在前面 简洁,是普罗大众所追求的一种精神。当我在编写文档的时候,当时还是用Windows系统,用Wor...
    写代码的海怪阅读 6,275评论 20 12
  • 常言道,“父爱如山,母爱如水”,母亲的爱像水一般温柔平静,细物无声,而父亲的爱,则如坚毅的山峰,沉稳、内敛而...
    Katetongtong阅读 321评论 0 2