leetcodeTop100好题

L5_最长回文子串

 //动态规划
    public static String longestPalindrome1(String s) {
        if (s.length() < 2) {
            return s;
        }
        int maxLen = 0, begin = 0;
        boolean[][] dp = new boolean[s.length() + 1][s.length() + 1];
        for (int L = 2; L <= s.length(); L++) {
            for (int i = 0; i < s.length(); i++) {
                int j = L + i - 1;
                //此时表示当前长度L下,继续遍历i已经不可能再符合条件
                if (j >= s.length()) {
                    break;
                }
                if (s.charAt(i) != s.charAt(j)) {
                    dp[i][j] = false;
                } else {
                    if (j - i < 3) {
                        dp[i][j] = true;
                    } else {
                        dp[i][j] = dp[i + 1][j - 1];
                    }
                }
                if (dp[i][j] && j - i + 1 > maxLen) {
                    maxLen = j - i + 1;
                    begin = i;
                }
            }
        }
        return s.substring(begin, begin + maxLen);
    }
//中心扩展

//马拉车
上一篇:Android RecyclerView 横屏禁用滚动/竖屏开启滚动


下一篇:类与对象的小结