Day 60 | 动态规划 647. 回文子串 、 516.最长回文子序列 、动态规划总结篇

647. 回文子串

题目
文章讲解
视频讲解

java 复制代码
class Solution {
    public int countSubstrings(String s) {
        char[] chars = s.toCharArray();
        int len = chars.length;
        boolean[][] dp = new boolean[len][len];
        int result = 0;
        for (int i = len - 1; i >= 0; i--) {
            for (int j = i; j < len; j++) {
                if (chars[i] == chars[j]) {
                    if (j - i <= 1) { // 情况一 和 情况二
                        result++;
                        dp[i][j] = true;
                    } else if (dp[i + 1][j - 1]) { //情况三
                        result++;
                        dp[i][j] = true;
                    }
                }
            }
        }
        return result;
    }
}

516.最长回文子序列

题目
文章讲解
视频讲解

java 复制代码
public class Solution {
    public int longestPalindromeSubseq(String s) {
        int len = s.length();
        int[][] dp = new int[len + 1][len + 1];
        for (int i = len - 1; i >= 0; i--) { // 从后往前遍历 保证情况不漏
            dp[i][i] = 1; // 初始化
            for (int j = i + 1; j < len; 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], Math.max(dp[i][j], dp[i][j - 1]));
                }
            }
        }
        return dp[0][len - 1];
    }
}

动态规划总结篇

文章讲解

相关推荐
Liu_Meihao2 小时前
【算法】799. 最长连续不重复子序列
数据结构·算法
正在敲代码中3 小时前
变换队列c++
数据结构·c++·算法
yonuyeung5 小时前
代码随想录算法【Day57】
数据结构·算法
居然有人6545 小时前
27.贪心算法5
算法·贪心算法
夏末秋也凉6 小时前
力扣-动态规划-62 不同路径
算法·leetcode·动态规划
工大一只猿6 小时前
贪心算法-455分发饼干
算法·贪心算法
pljnb7 小时前
【LeetCode 热题100】 240. 搜索二维矩阵 II的算法思路及python代码
算法·leetcode·矩阵
迷茫小玄森7 小时前
【R语言】Kmeans算法
算法·r语言·kmeans
居然有人6547 小时前
25.贪心算法3
算法·贪心算法
夏末秋也凉9 小时前
力扣-动态规划-70 爬楼梯
算法·leetcode·动态规划