5.最长回文子串

最长回文子串.png
动态规划
class Solution {
    public String longestPalindrome(String s) {
        char[] cs = s.toCharArray();
        boolean[][] dp = new boolean[cs.length][cs.length];

        int maxLen = 1;
        int begin = 0;

        for (int i = cs.length - 1; i >= 0; i--) {
            for (int j = i; j < cs.length; j++ ) {
                int len = j - i + 1;
                dp[i][j] = (cs[i] == cs[j]) && (len <= 2 || dp[i+1][j-1]);
                if (dp[i][j] && len > maxLen) {
                    maxLen = len;
                    begin = i;
                }
            }
        }
        return new String(cs,begin,maxLen);
    }
}

你可能感兴趣的:(5.最长回文子串)