51nod 1089 - 最长回文子串 V2(Manacher算法)- Manacher模板题

1089 最长回文子串 V2(Manacher算法)

Time Limit: 1000 MS                                    Memory Limit: 131,072.0 KB

题目描述 

回文串是指aba、abba、cccbccc、aaaa这种左右对称的字符串。

输入一个字符串Str,输出Str里最长回文子串的长度。

输入

输入Str(Str的长度 <= 100000)

输出

输出最长回文子串的长度L。

输入样例

daabaac

输出样例

5

代码

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 1e5 + 10;
char s[N], ma[N << 1];
int p[N << 1];
void manacher(char *s, int len){
    int l = 0;
    ma[l ++] = '$';
    ma[l ++] = '#';
    for (int i = 1; i <= len; ++ i){
        ma[l ++] = s[i];
        ma[l ++] = '#';
    }
    ma[l] = 0;
    int r = 0, c = 0;
    for (int i = 0; i <= l; ++ i){
        p[i] = r > i ? min(p[2 * c - i], r - i) : 1;
        while (ma[i - p[i]] == ma[i + p[i]]) ++ p[i];
        if (i + p[i] > r){
            r = i + p[i];
            c = i;
        }
    }
}
int main()
{
    scanf("%s", s + 1);
    int len = strlen(s + 1);
    manacher(s, len);
    int ans = 0;
    for (int i = 1; i <= 2 * len + 1; ++ i){
        ans = max(ans, p[i] - 1);
    }
    printf("%d\n", ans);
    return 0;
}
发布了21 篇原创文章 · 获赞 0 · 访问量 822

猜你喜欢

转载自blog.csdn.net/tourist1412/article/details/105039936