647. 回文子串 Palindromic Substrings - LeetCode
dp[i][j] [i,j]范围内的子串是否是回文子串
1.i == j
2.i j相差1
3. j - 1 > i dp[i - 1][j - 1]
if (s[i] ==s[j])
if (j - i <= 1) dp[i][j] = true; res++;
else if (dp[i - 1][j - 1] == true) dp[i][j] = true; res++;
初始化:dp[i][j]
dp[i][j] = false
遍历顺序: 从低往上,从左往右
for (int i = size() - 1; i >= 0; i--)
for (int j = i; j < s.length(); j++)
class Solution {public int countSubstrings(String s) {int n = s.length();boolean[][] dp = new boolean[n][n];// dp[0][0] = false;int res = 0;for (int i = s.length() - 1; i >= 0; i--) {for (int j = i; j < s.length(); j++) {if (s.charAt(i) == s.charAt(j)) {if (j - i <= 1) {dp[i][j] = true;res++;} else if (dp[i + 1][j - 1]) {dp[i][j] = true;res++;}}}}return res;}
}
● 516.最长回文子序列 Longest Palindromic Subsequence - LeetCode
dp[i][j] [i,j]的回文子串并列长度为
if (s[i] == s[j]) dp[i][j] = dp[i + 1][j - 1] + 2//左右都加了一个元素
else dp[i][j] = max(dp[i][j - 1], dp[i + 1][j])
初始化: dp[i][i] = 1;
for (int i = 0; i < s.length(); i++)
dp[i][i] = 1;
遍历顺序:
for (i < s.length() - 1; i >= 0; i--)
for (int j = i + 1; j < s.length(); j++)
class Solution {public int longestPalindromeSubseq(String s) {int[][] dp = new int[s.length()][s.length()];for (int i = 0; i < s.length(); i++) {dp[i][i] = 1;}for (int i = s.length() - 1; i >= 0; i--) {for (int j = i + 1; j < s.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][s.length() - 1];}
}
● 动态规划总结篇