这个最长子回文问题,有很多种解法,这里还是再加上动态规划的解法吧。
题目:
求字符串的最大会问子串;
Given a string
s
, return the longest palindromic substring ins
.给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
示例 1:
输入: "babad" 输出: "bab" 注意: "aba" 也是一个有效答案。 示例 2:
输入: "cbbd" 输出: "bb"
解题分析:动态规划 + dp数组 + 状态转义方程;
class Solution {public String longestPalindrome(String s) {int n = s.length();String result = "";// dp[i][j] indicates whether substring s starting at index i and ending at j is palindromeboolean[][] dp = new boolean[n][n];for(int i = n - 1; i >=0; i--){ // keep increasing the possible palindrome stringfor(int j = i; j < n; j++){ // find the max palindrome within this window of (i,j)/**当i和j在2个索引距离之内时,它只是排除条件dp [i + 1] [j-1]。简而言之,如果i == j,则dp [i] [j] = s.charAt(i)== s.charAt(j)i + 1 == j,则dp [i] [j] = s.charAt( i)== s.charAt(j)i + 2 == j,dp [i] [j] = s.charAt(i)== s.charAt(j),因为中间的那个无所谓。仅当i + 3 == j时,dp [i] [j] = s.charAt(i)== s.charAt(j)&& dp [i + 1] [j-1];*/// chars at i and j should match;// j-i < 3, if window is less than or equal to 3, just end chars should match// if window is > 3, substring (i+1, j-1) should be palindrome toodp[i][j] = s.charAt(i) == s.charAt(j) && (j - i <3 || dp[i + 1][j - 1]);//update max palindrome stringif(dp[i][j] && (result == null || j-i+1 > result.length())){result = s.substring(i, j+1);}}}return result;}
}