Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
题目描述:给定字符串,求出最大的回文串,结果可能有多种,返回一种即可;
算法分析:
采用动态规划的思想,用二维数组DP[j][i]来表示第j个字符到第i个字符是否是回文,因此可以用两个for循环来解决填表问题,填表的时候应当使i、j从同一点开始,一次循环中,保证i不动,j从i往前直到0,这样才能保证动态规划表达式的正确性。动态规划表达式为DP[j][i]=(DP[j+1][i-1] | | i-j<=2)&&s[i]==s[j]
代码:
class Solution { public String longestPalindrome(String s) { if(s==null) return ""; boolean[][] dp = new boolean[s.length()][s.length()]; int maxLen=0; String res=""; for(int i=0;i<s.length();i++){ for(int j=i;j>=0;j--){ if(s.charAt(j)==s.charAt(i)&&(i-j<2||dp[j+1][i-1])){ dp[j][i]=true; if(i-j+1>maxLen){ maxLen=i-j+1; res=s.substring(j,i+1); } } } } return res; } }