动态规划 最长回文子串

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

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

Example 2:

Input: "cbbd"
Output: "bb"



public static String longestPalindrome(String s) {
        int n = s.length();
        if(n==0 || s==null)
            return s;
        String reString = null;
        boolean[][] dp = new boolean[n][n];
        for(int i = n-1;i >= 0; i--) {
            for(int j = i; j < n; j++) {
                dp[i][j] = s.charAt(i)==s.charAt(j)&&(j-i<3 || dp[i+1][j-1]);    //判断是否为回文串
                if(dp[i][j] && (reString==null || reString.length()<j-i+1))   //判断这个回文串的长度是否大于最长长度
                    reString = s.substring(i,j+1);
            }
        }
        return reString;
    }

使用boolean创建一个二维数组dp[][],dp[i][j]的值代表从第i个字符到第j个字符的字符串是否为回文串。

首先判定一个字符串是回文串有什么特点,如果dp[i][j]是回文串,那么dp[i+1][j-1]也是回文串,由此我们可以得出:

 dp[i][j] = s.charAt(i)==s.charAt(j)&&(j-i<3 || dp[i+1][j-1])
posted @ 2018-09-20 10:39  天地鸥  阅读(1200)  评论(1编辑  收藏  举报