647 回文子串
https://leetcode.cn/problems/palindromic-substrings/
class Solution { //TO(n^2) SO(n^2) DP记录是不是回文,全局变量result统计几个;而不是用dp来统计
public int countSubstrings(String s) {
boolean[][] dp = new boolean[s.length()][s.length()];
int result = 0;
for (int j = 0; j < s.length(); j++) {
for (int i = 0; i <= j; i++) {
if (i == j) {
dp[i][j] = true;
result++;
} else if (s.charAt(i) == s.charAt(j) && (i == j - 1 || dp[i + 1][j - 1])){
dp[i][j] = true;
result++;
}
}
}
return result;
}
}
class Solution { //TO(n^2) SO(1) 中心开花
public int countSubstrings(String s) {
int result = 0;
for (int i = 0; i < s.length(); i++) {
result += extend(s, i, i);
}
for (int i = 0; i + 1 < s.length(); i++) {
result += extend(s, i, i + 1);
}
return result;
}
private int extend(String s, int i, int j) {
int result = 0;
while (i >= 0 && j < s.length()) {
if (s.charAt(i) == s.charAt(j)) {
result++;
i--;
j++;
} else {
return result;
}
}
return result;
}
}
516 最长回文子序列
https://leetcode.cn/problems/longest-palindromic-subsequence/
class Solution { // 两头相等时 dp[i][j] = dp[i + 1][j - 1] + 2 ,不等时 max(dp[i + 1][j], dp[i][j - 1])
public int longestPalindromeSubseq(String s) {
int[][] dp = new int[s.length()][s.length()];
for (int i = s.length() - 1; i >= 0; i--) {
for (int j = i; j < s.length(); j++) {
if (i == j) {
dp[i][j] = 1;
// } else if (i + 1 == j){
// dp[i][j] = s.charAt(i) == s.charAt(j) ? 2 : 1; //两头不等为1不是0,这个i==j - 1的初始化也可省略,因为dp[i + 1][j - 1]是坐下角为0的dp元素
} else 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][s.length() - 1];
}
}