Manacher算法

博客介绍了Manacher算法,该算法可在O(n)时间内求出一个字符串的最长回文子串,还给出了教学视频链接,并列举了HDU - 3068这一例题,内容转载自相关博客。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Manacher

可以在\(O(n)\)的时间内求一个字符串的最长回文子串。

教学视频链接

例题

HDU - 3068

#include <bits/stdc++.h>

#define FOPI freopen("in.txt", "r", stdin)
#define FOPO freopen("out.txt", "w", stdout)
#define FOR(i,x,y) for (int i = x; i <= y; i++)
#define ROF(i,x,y) for (int i = x; i >= y; i--)

using namespace std;
typedef long long LL;
const int inf = 0x3f3f3f3f;
const int maxn = 2e5 + 100;

char Ma[maxn*2];
int Mp[maxn*2];

void Manacher(char s[], int len)
{
    int l = 0;
    Ma[l++] = '$';
    Ma[l++] = '#';
    FOR(i, 0, len-1) Ma[l++] = s[i], Ma[l++] = '#';
    Ma[l] = 0;

    int mx = 0, id = 0;
    FOR(i, 0, l-1)
    {
        Mp[i] = mx > i ? min(Mp[2*id-i], mx-i) : 1;
        while(Ma[i+Mp[i]] == Ma[i-Mp[i]]) Mp[i]++;
        if (i+Mp[i] > mx) mx = i+Mp[i], id = i;
    }
}

char s[maxn];
int main()
{
    while(~scanf("%s", &s))
    {
        int len = strlen(s);
        Manacher(s, len);
        int ans = 0;
        FOR(i, 0, 2*len+2-1) ans = max(ans, Mp[i]-1);
        printf("%d\n", ans);
    }
}

转载于:https://www.cnblogs.com/ruthank/p/10910527.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值