leetcode5.Longest Palindromic Substring

返回最长回文串

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

解题思路:定义下标i,j,boolean dp[i][j]

动态规划思想:要求大的,先求小的

  1. 边界:dp[i][j] = true
    1. i ==j 单个字符一定为true
    2. str[i] == str[j]&&j-i ==1 两个挨着的字符相等,一定为true.
  2. 状态转移公式:dp[i][j] = str[i] == str[j] && dp[i+1][j-1]
public String longestPalindrome(String s) {
        if (s == null || s.isEmpty()) {
            return null;
        }
        boolean[][] mins = new boolean[s.length()][s.length()];
        int maxLen = 0;
        String maxStr = null;
        for (int len = 1; len <= s.length(); len++) {
            for (int i = 0; i + len <= s.length(); i++) {
                int j = i + len - 1;
                if (len == 1) {
                    mins[i][j] = true;
                } else if (len == 2) {
                    mins[i][j] = s.charAt(i) == s.charAt(j);
                } else {
                    mins[i][j] = s.charAt(i) == s.charAt(j) && mins[i + 1][j - 1];
                }

                if (mins[i][j] && len > maxLen) {
                    maxLen = len;
                    maxStr = s.substring(i, i + len);
                }
            }
        }
        return maxStr;

    }
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页