二刷hot100-1143.最长公共子序列

状态转移方程:

if(ch1i - 1 == ch2j - 1){

dpij = dpi - 1j - 1 + 1;

}else{

dpij = Math.max(dpij-1,dpi-1j);

}

dp数组的含义:表示长度为i-1和j-1的两个字符串的最长公共子序列;

java 复制代码
class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        char[] ch1 = text1.toCharArray();
        char[] ch2 = text2.toCharArray();
        int[][] dp = new int[ch1.length + 1][ch2.length + 1];
        for(int i = 0;i < dp.length;i++){
            for(int j = 0;j < dp[0].length;j++){
                if(i == 0 || j == 0){
                    dp[i][j] = 0;
                }
            }
        }
        for(int i = 1;i < dp.length;i++){
            for(int j = 1;j < dp[0].length;j++){
                if(ch1[i - 1] == ch2[j - 1]){
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                }else{
                    dp[i][j] = Math.max(dp[i][j-1],dp[i-1][j]);
                }
            }
        }
        return dp[ch1.length][ch2.length];
    }
}
相关推荐
Pniubi4 小时前
01背包类问题-力扣416.分割等和子集
算法·leetcode·职场和发展
文丑颜不良啊14 小时前
LeetCode3041~3060题目解析
java·leetcode
罗西的思考15 小时前
【轻量化复现大模型 / KIMI K3】MTP / EAGLE‑3 模块交互式演示
人工智能·深度学习·算法
文丑颜不良啊16 小时前
LeetCode3101~3120题目解析
java·leetcode
kyle~19 小时前
模型预测控制(MPC)
算法·机器人·控制·传感器
牢姐与蒯20 小时前
cpp算法之哈希
c++·算法·哈希算法
开开心心就好21 小时前
两张表格数据对比工具,不用写函数也能查
算法·spring·智能手机·pdf·电脑·intellij-idea·音视频
电科_银尘1 天前
【大模型算法与工程 02】线性回归与逻辑回归:从损失函数到决策边界
算法·逻辑回归·线性回归
玄昌盛不会编程1 天前
LeetCode——2243. 计算字符串的数字和
java·算法·leetcode
文丑颜不良啊1 天前
LeetCode3061~3080题目解析
java·leetcode