LeetCode-5

class Solution {
public:
    string longestPalindrome(string s) {
        int bound = 0;
        int id, max_pos = 0;
        int new_len = 2*s.length() + 2;
        vector<int> P(new_len, 1);
        string new_str(new_len-1, '#');
        //生成新串,用#填充
        for(int i=0; i<s.length(); i++){
            new_str[2*i+1] = s[i];
        }
        new_str = '$' + new_str + '\0'; //防止越界
        //manacher算法
        for(int i=1; i<new_len; i++)
        {
            if(i < bound)
            {
                P[i] = min(bound-i, P[2*id-i]);    
            }
            while(new_str[i-P[i]] == new_str[i+P[i]])
            {
                P[i]++;
            }
            //更新id和bound
            if(i+P[i] > bound)
            {
                bound = i+P[i];
                id = i;
            }
            max_pos = P[i] > P[max_pos]?i:max_pos;
        }
        int len = P[max_pos]-1;
        int start = (max_pos-P[max_pos])/2;
        return s.substr(start,len);
        
    }
};

bound:当前回文字符串右端最大值;

id:回文字符串右端最大值的中心点;

max_pos:当前最长回文字符串的中心位置;

P[i]:即计算以i位置为中心的最长回文字符串右端到i的距离。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值