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[i][j] 表示从i开始到j结束的子串是否是回文
* 可以得出以下递推式
* when j == i + 1 如果s[j] == s[i] 则该子串为回文 dp[i][j] = 1
* when j > i +1 需要满足 s[j] == s[i] 和 dp[i+1][j-1] ==1 两个条件
* @param s
* @return
*/
public static String longestPalindrome(String s) {
char[] arr = s.toCharArray();
int maxlen = s.length() +5;
int len = 0;
int start = 0;
int end = 0;
int [][] dp = new int[maxlen][maxlen];
for(int j = 0; j < arr.length;j++){
for(int i = 0; i < j;i++){
if(arr[i] == arr[j] && (j - i < 2 || dp[i+1][j-1] == 1)){
dp[i][j] = 1;
}
if(dp[i][j] == 1 && len < j - i +1){
len = j - i +1;
start = i;
end = j;
}
}
dp[j][j] = 1;
}
return s.substring(start,end+1);
}