【LeetCode 5】 最长回文子串

题目链接
描述

【题解】

[一个讲得比较好的博客地址](https://www.cnblogs.com/lykkk/p/10460087.html); 感觉manacher算法的大概思路就是利用回文串左右对称的性质。 利用之前算出来的以某个点为中心的回文串。而当前要枚举的串被包括在其中。 则可以用左半部分的结果来获取右边当前的串的结果。 O(N) 当然也可以枚举中间点在哪个地方然后O(N^2)求。

【代码】

class Solution {
public:
    const int N = 1000;
    
    string getSpecialString(string s){
        string temp = "#";
        int len = s.size();
        for (int i = 0;i < len;i++){
            temp = temp + s[i];
            temp = temp + "#";
        }
        return temp;
    }
    
    string longestPalindrome(string s) {
        int p[N*2+10];
        memset(p,0,sizeof p);
        s = getSpecialString(s);
        int ma = -1,id = -1;
        int len = s.size();
        for (int i = 0;i < len;i++){
            if (i>ma){
                p[i] = 1;
            }else{//i<=ma
                //这种情况里面也有可以继续扩展的情况
                p[i] = min(ma-i+1,p[2*id-i]);
            }
            while (i-p[i]>=0 && i+p[i]<len && s[i-p[i]]==s[i+p[i]]){
                if (i+p[i]>ma){//更新最右边界
                    ma = i+p[i];
                    id = i;
                }
                p[i]++;
            }
        }
        int ansindex = 0;
        for (int i = 1;i < len;i++)
            if (p[ansindex]<p[i]){
                ansindex = i;
            }
        string t = "";
        for (int i = ansindex-p[ansindex]+1;i<=ansindex+p[ansindex]-1;i++){
            if (s[i]!='#'){
                t+=s[i];
            }
        }
        return t;
    }
};
原文地址:https://www.cnblogs.com/AWCXV/p/11784793.html