647. 回文子串
动态规划解决的经典题目,如果没接触过的话,别硬想 直接看题解。
class Solution {
public int countSubstrings(String s) {
char[] array = s.toCharArray();
int length = array.length;
boolean[][] dp = new boolean[length][length];
int count = 0;
for (int start = length - 1; start >= 0; start--) {
for (int end = start; end < length; end++) {
if (array[start] == array[end]) {
if (end - start <= 1) {
count++;
dp[start][end] = true;
} else if (dp[start + 1][end - 1]) {
count++;
dp[start][end] = true;
}
}
}
}
return count;
}
}
516.最长回文子序列
647. 回文子串,求的是回文子串,而本题要求的是回文子序列, 大家要搞清楚两者之间的区别。
public class Solution {
public int longestPalindromeSubseq(String s) {
int length = s.length();
int[][] dp = new int[length + 1][length + 1];
for (int i = length - 1; i >= 0; i--) {
dp[i][i] = 1;
for (int j = i + 1; j < length; j++) {
if (s.charAt(i) == s.charAt(j)) {
dp[i][j] = dp[i + 1][j - 1] + 2;
} else {
dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][length - 1];
}
}