Theme Section (HDU - 4763 )

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

AC代码:

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 10;
char s[maxn];
int Next[maxn];

void prekmp(int len)
{
    int k = -1;
    Next[0] = -1;
    for(int i = 1; i < len; i++)
    {
        while(k > -1 && s[k+1] != s[i])
        {
            k = Next[k];
        }
        if(s[k+1] == s[i])
        {
            k++;
        }
        Next[i] = k;
    }
}

int kmp(int len)
{
    int L = strlen(s);
    int k = -1;
    for(int i = len-1; i < L-len; i++)
    {
        while(k > -1 && s[k+1] != s[i])
        {
            k = Next[k];
        }
        if(s[k+1] == s[i])
        {
            k++;
        }
        if(k+1 == len)
        {
            return len;
        }
    }
    return -1;
}

int main()
{
    int T;
    scanf("%d", &T);
    getchar();
    while(T--)
    {
        scanf("%s", s);
        int len = strlen(s), ans = 0;
        if(len < 3)
        {
            puts("0");
            continue ;
        }
        prekmp(len);
        int t = Next[len-1];
        /*
        for(int i = 0; i < len; i++)
        {
            cout << Next[i] << " ";
        }
        cout << endl;
        */
        while(t != -1)
        {
            //cout << kmp(t+1) << " ";
            if(kmp(t+1) != -1)
            {
                ans = max(ans, t+1);
            }
            t = Next[t];
        }
        //cout << endl;
        printf("%d\n", ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/MALONG11124/article/details/81835842