Longest Palindromic Substring

Description:
Given a string S, find the longest palindromic substring in S.
You may assume that the maximum length of S is 1000, and there exist
one unique longest palindromic substring.

分析见:
https://segmentfault.com/a/1190000003914228

 #include <iostream>
 #include <string>

using namespace std;

int manacher(string str)  //manacher算法 求最长回文字符串
{
    //插入没有在数组中出现的符号,这里用"#", abba->#a#b#b#a#
    string NewStr;
    NewStr += "#";
    for (int i=0; i < str.size(); i++)
    {
        NewStr += str[i];
        NewStr += "#";
    }

    int RL[NewStr.size()];    //回文半径数组
    int MaxRight = 0, pos = 0, Maxlen = 0;

    for(int i = 0; i < NewStr.size(); i++){
        if ( i < MaxRight)
            RL[i] = min(RL[2*pos-i],MaxRight-i);
        else
            RL[i] = 1;

        //扩展,注意边界
        while ((i-RL[i] >= 0) && (i+RL[i] < NewStr.size()) && (NewStr[i-RL[i]] == NewStr[i+RL[i]])) {
            RL[i] += 1;
        }

        //更新MaxRight,pos
        if ((i+RL[i]-1) > MaxRight)
        {
            MaxRight = i+RL[i]-1;
            pos = i;
        }

        //更新最长回文串的长度
        Maxlen = max(Maxlen,RL[i]);
    }

    return Maxlen-1;
}

int main(int argc, char const *argv[]) {

    string str = "abba";
    string str2 = "123454321";
    string str3 = "acdeg";

    std::cout <<manacher(str)<< std::endl;
    std::cout <<manacher(str2)<< std::endl;
    std::cout <<manacher(str3)<< std::endl;

    return 0;
}

测试:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值