[LeetCode 5] palindromic longest substring

Topic Link
Description

【answer】


Put a good blog address ;
feeling manacher algorithm is probably the idea is to use a palindrome string symmetrical nature.
Counted out before use to a certain point as the center of the palindrome string. To enumerate the current string is included therein.
The results can be used to obtain the results of the left half of the right of the current string.
O (N)
may of course be enumerated and O (N ^ 2) where to find the middle point.

[Code]

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;
    }
};

Guess you like

Origin www.cnblogs.com/AWCXV/p/11784793.html