HDOJ3068最长回文

最长回文

解法1、manacher算法

#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
char str[1000002 + 1200];

int fast(char *p) {
    int ans = 1;
    for (int i = 1; p[i]; ++i) {
        int s = i, e = i, t;
        while (p[e + 1] == p[i]) ++e;
        i = e;
        while (p[s - 1] == p[e + 1]) --s, ++e;
        if ((t = e - s + 1) > ans) ans = t;
    }
    return ans;
}

int main() {
    str[0]='$';

    while(scanf("%s", str+1) !=EOF) {
        printf("%d\n", fast(str));
    }
    return 0;
}
View Code

 

解法2、后缀树

#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
char str[1000002 + 1200];

int fast(char *p) {
    int ans = 1;
    for (int i = 1; p[i]; ++i) {
        int s = i, e = i, t;
        while (p[e + 1] == p[i]) ++e;
        i = e;
        while (p[s - 1] == p[e + 1]) --s, ++e;
        if ((t = e - s + 1) > ans) ans = t;
    }
    return ans;
}

int main() {
    str[0]='$';

    while(scanf("%s", str+1) !=EOF) {
        printf("%d\n", fast(str));
    }
    return 0;
}
View Code

 

posted on 2016-07-04 21:23  disppr  阅读(172)  评论(0编辑  收藏  举报