1. 题目
2. 思路
(1) 动态规划
- dp[i][j]表示下标为[i,j]的子串是否是回文串。
- 若子串两端的字符相等,且中间的子串是回文串,则该子串也是回文串,同时维护一个全局变量,表示最长回文子串的长度。
- 外层循环从后往前遍历,内层循环从前往后遍历,保证子串内的任意子串已经被判断过。
3. 代码
public class Test {
public static void main(String[] args) {
}
}
class Solution {
public int getLongestPalindrome(String A) {
char[] chars = A.toCharArray();
int n = chars.length;
boolean[][] dp = new boolean[n][n];
int res = 1;
for (int i = n - 1; i >= 0; i--) {
dp[i][i] = true;
for (int j = i + 1; j < n; j++) {
if (chars[i] == chars[j]) {
if (i + 1 == j) {
dp[i][j] = true;
res = Math.max(res, 2);
} else if (dp[i + 1][j - 1]) {
dp[i][j] = true;
res = Math.max(res, j - i + 1);
}
} else {
dp[i][j] = false;
}
}
}
return res;
}
}