您的位置:首页 > 其它

hdu 4763 Theme Section(kmp)

2015-09-06 21:46 411 查看
题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=4763

解题思路:

题目大意:

给你一个字符串,问你是否可以表示为“EAEBE”的形式,E、A、B表示一个字符串,可以为空,输出最长的E串的长度。

解题思路:

KMP,首先先求出最长后缀,然后用KMP算法判断去掉前后部分后是否存在该串,不存在则缩小长度,直到为0为止。。。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

const int maxn = 1000005;
int len,Next[maxn];
char str[maxn];

void getNext(){
    int j = 0,k = -1;
    Next[0] = -1;
    while(j < len){
        if(k==-1 || str[j]==str[k]){
            j++; k++;
            Next[j] = k;
        }
        else
            k = Next[k];
    }
}

int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        scanf("%s",str);
        len = strlen(str);
        getNext();
        int k = Next[len],ans = 0;
        while(k && !ans){
            int j = 0;
            for(int i = k; i < len-k; i++){
                if(j == k)
                    break;
                while(!(j==-1 || str[i]==str[j]))
                    j = Next[j];
                j++;
            }
            if(j == k)
                ans = k;
            k = Next[k];
        }
        printf("%d\n",ans);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: