Leetcode5[Med] 最长回文字串-DP

Leetcode5[Med] 最长回文字串-DP

思路借鉴:DP,下面是 Python代码.

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        matrix = [[0 for i in range(len(s))] for i in range(len(s))] //initialize matrix to keep track of the state
        result = "" //record longest sequence
        max_len = 0 //record longest length
        for j in range(len(s)):
            for i in range(0, j+1):
                if j - i <=1: //i=j or i,j 相邻 即考虑:a或bb情况
                    if s[i] == s[j]: 
                        matrix[i][j] = True
                        if max_len < j-i+1:
                            result = s[i:j+1]
                            max_len = j - i + 1
                else: //考虑abba情况
                    if s[i] == s[j] and matrix[i+1][j-1]:
                        matrix[i][j] = True
                        if max_len < j-i+1:
                            result = s[i:j+1]
                            max_len = j - i + 1
        return result

下面是 Java代码.

class Solution {
    public String longestPalindrome(String s) {
        int len = s.length();
        boolean[][] dp = new boolean[len][len];
        String result = "";
        int max_len = 0;
        for(int j=0; j<len; j++){
            for(int i=0; i<=j; i++){
                if (j-i <=1){
                    if (s.charAt(i) == s.charAt(j)){
                        dp[i][j] = true;
                        if(max_len<j-i+1){
                            result = s.substring(i,j+1);
                            max_len = j - i + 1;
                        }
                    }
                    
                }
                else{
                    if (s.charAt(i)==s.charAt(j) && dp[i+1][j-1]){
                        dp[i][j] = true;
                        if(max_len<j-i+1){
                            result = s.substring(i,j+1);
                            max_len = j - i + 1;
                        }
                    }
                }
            }
        }
        return result;
        
        
    }
}

你可能感兴趣的:(动态规划)