LeetCode题解之动态规划(longest-palindromic-substring)

longest-palindromic-substring

class Solution {
public:
    /*
    动态规划求解最长回文串 时间复杂度为O(n^2)
    dp[i][j]为true表示下标i~j的子串是回文串
    
    以str="eabcbaf"为例,二维dp表如下
         e    a    b    c    b    a    f
    e    1    0    0    0    0    0    0
    a         1    0    0    0    1    0
    b              1    0    1    0    0
    c                   1    0    0    0
    b                        1    0    0
    a                             1    0
    f                                  1
    当j=4,i=2时,更新left=2,right=4,maxLen=3
    当j=5,i=1时,更新left=1,right=5,maxLen=5
    */
    string longestPalindrome(string str) {
        int len = str.length();
        if (len == 0) return "";
        vector > dp(len, vector(len, false));
        //left为最长回文子串的左边界,right为右边界,maxLen为最长回文串长
        int left = 0, right = 0, maxLen = 0;
        for (int j = 0; j < len; j++) { //列
            dp[j][j] = true;
            for (int i = 0; i < j; ++i) { //行
                dp[i][j] = (str[i] == str[j] && (j - i < 2 || dp[i + 1][j - 1]));
                if (dp[i][j] && (j - i + 1 > maxLen)) {
                    left = i;
                    right = j;
                    maxLen = j - i + 1;
                }
            }
        }
        return str.substr(left, right - left + 1);
    }
};

你可能感兴趣的:(算法,c++,刷题)