letcode5 最长回文子串(未写代码)

参考:
https://leetcode.com/problems/longest-palindromic-substring/discuss/147548/Direct-c%2B%2B-DP

https://www.cnblogs.com/leavescy/p/5878336.html

class Solution {
public:
    string longestPalindrome(string s) {
        if(s.size()==0) return "";
        int i = 0, j = 0;
        int n = s.size();
        //initialize P[n][n], we only need half of P, and initialize it like: (e.g. : s="abbc")
        bool P[n][n]={false};
        for(int x = 0;x<n;x++){
            P[x][x]=true;  //斜对角赋值true,因为一个字母肯定是回文串
            if(x==n-1) break;
            P[x][x+1] = (s[x]==s[x+1]);//斜对角的横向下一个元素赋值,即第i-i+1的串,当两个字母相等时为回文串
        }
        //dp 
        for(int i = n-3; i>=0; --i){ //从右下角第一个没填的位置开始填充
            for(int j = i+2;j<n; ++j){
                P[i][j] = (P[i+1][j-1] && s[i]==s[j]); //当前位置的值取决于左下角的元素值
            }
        }
        //get maxstr result
        int max = 0;
        string maxstr = "";
        for(int i=0;i<n;i++){
            for(int j=i;j<n;j++){
                if(P[i][j]==true and j-i+1>max){  //找矩阵中连续为true的最长的序列
                    max = j-i+1;
                    maxstr = s.substr(i,j-i+1);
                }
            }
        }
        return maxstr;
    }
};```

你可能感兴趣的:(leetcode)