Leetcode Longest Palindromic Substring

OpenSoucre發表於2014-07-04

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

題目的意思:輸入一個字串S,找出其最長迴文串

用動態規劃求解

決策變數:dp[i][j]記錄從s[i]到s[j]組成的子串是否為迴文。

      dp[i+1][j-1]     , 當s[i]與s[j]相等時

dp[i][j] = 

      false      , 當s[i]與s[j]不相等時

單個字元是迴文串,故要初始化對角線

緊鄰的兩個相同字元也是迴文

 時間複雜度O(n^2)

class Solution {
public:
    string longestPalindrome(string s) {
        int n = s.length(), startIndex =  0, maxLen = 1;
        // vector<vector<bool> > dp(n,vector<bool>(n,false));
        bool dp[1000][1000] = {false};
        for(int i = 0 ; i < n; ++ i) dp[i][i] = true;
        for(int i = 0;  i < n-1; ++ i ){
            if(s[i] == s[i+1]){
                dp[i][i+1] = true;
                startIndex= i;
                maxLen = 2;
            }
        }
        for(int len = 3; len <= n; ++len){
            for(int i = 0 ; i < n-len+1; ++ i){
                int j = i+len-1;
                if(s[i] == s[j] && dp[i+1][j-1]){
                    dp[i][j] = true;
                    startIndex =i;
                    maxLen = len;
                }
            }
        }
        return s.substr(startIndex,maxLen);
    }
};
動態規劃求解

 利用Manacher 演算法求解,時間複雜度為O(n)

可以參考http://www.felix021.com/blog/read.php?2040

http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html

string preProcess(string s){
    int n = s.length();
    if( n == 0) return "^$";
    string res="^";
    for(int i = 0 ; i < n; ++ i) res+="#"+string(1,s[i]);
    res+="#$";
    return res;
}

string  longestPalindrome(string s){
    string T = preProcess(s);
    int n = T.length();
    vector<int> p(n,0);
    int center = 0, radius = 0,maxv = 0;
    for(int i = 1; i < n-1; ++ i){
        p[i] = (radius > i) ? min(radius-i,p[2*center-i]) : 0;
        while(T[i+1+p[i]] == T[i-1-p[i]]) p[i]++;
        if(i+p[i] > radius){
            center = i;
            radius = i+p[i];
        }
    }
    int maxLen = 0, centerIndex = 0;
    for(int i = 1; i < n-1; ++ i){
        if(p[i] > maxLen){
            maxLen = p[i];
            centerIndex = i;
        }
    }
    centerIndex = (centerIndex - 1-maxLen)/2;
    return s.substr(centerIndex,maxLen);
}
Manacher演算法

 

 

  

相關文章