动态规划避免重复计算,讲计算过的存下来,空间换时间
//动态规划
public static String longstPalindrome(String s) {
int strLen = s.length();
int maxLen = 0;
int maxStart = 0;
int maxEnd = 0;
//dp[i,j] 从i到j的最长回文子串为true,那么i-1到j+1时,如i-1等于j-1,则也为true
boolean[][] dp = new boolean[strLen][strLen];
for (int r = 1; r < strLen; r++) {
for (int l = 0; l < r; l++) {
if (s.charAt(l) == s.charAt(r) && (r - l <= 2 || dp[l + 1][r - 1])) {
dp[l][r] = true;
if (r - l + 1 > maxLen) {
maxLen = r - l + 1;
maxStart = l;
maxEnd = r;
}
}
}
}
return s.substring(maxStart, maxEnd + 1);
}