day03:最长回文子串(Java)

class Solution {
    public String longestPalindrome(String s) {
        // 边界判断
        if (s == null || s.length() == 0)
            return s;
        
        int len = s.length();
        int l = 0, r = 0;
        boolean[][] mat = new boolean[len][len];

        for (int j = 0; j < len; j++)
            // i <= j,mat矩阵对角对称,取矩阵上三角即可
            for (int i = 0; i <= j; i++) {
                // 动态规划递推式,当子串长度为1,2时,j-i < 2 ;当子串长度等于大于3时,mat[i+1][j-1]。
                mat[i][j] = s.charAt(i)==s.charAt(j) && (j-i < 2 || mat[i+1][j-1]);
                if (mat[i][j] && j - i > r - l) {
                    l = i;
                    r = j;
                }
            }
        return s.substring(l, r + 1);
    }
}

参考以下资料:

https://www.cnblogs.com/baiqiantao/p/10094520.html

https://mp.weixin.qq.com/s/D72qugTLpgITU6IJ1QQERg

https://segmentfault.com/a/1190000002991199

你可能感兴趣的:(leetcode)