LeetCode1143. Longest Common Subsequence——动态规划

文章目录

一、题目

Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

For example, "ace" is a subsequence of "abcde".

A common subsequence of two strings is a subsequence that is common to both strings.

Example 1:

Input: text1 = "abcde", text2 = "ace"

Output: 3

Explanation: The longest common subsequence is "ace" and its length is 3.

Example 2:

Input: text1 = "abc", text2 = "abc"

Output: 3

Explanation: The longest common subsequence is "abc" and its length is 3.

Example 3:

Input: text1 = "abc", text2 = "def"

Output: 0

Explanation: There is no such common subsequence, so the result is 0.

Constraints:

1 <= text1.length, text2.length <= 1000

text1 and text2 consist of only lowercase English characters.

二、题解

cpp 复制代码
class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        int n = text1.size(),m = text2.size();
        vector<vector<int>> dp(n+1,vector<int>(m+1,0));
        for(int i = 1;i <= n;i++){
            for(int j = 1;j <= m;j++){
                if(text1[i - 1] == text2[j - 1]) dp[i][j] = 1 + dp[i-1][j-1];
                else dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
            }
        }
        return dp[n][m];
    }
};
相关推荐
呼啦啦啦啦啦啦啦啦3 小时前
常见的排序算法
java·算法·排序算法
胡萝卜3.04 小时前
数据结构初阶:排序算法(一)插入排序、选择排序
数据结构·笔记·学习·算法·排序算法·学习方法
地平线开发者5 小时前
LLM 中 token 简介与 bert 实操解读
算法·自动驾驶
lyx33136967595 小时前
Pandas数据结构详解Series与DataFrame
数据结构·pandas
scx201310045 小时前
20250814 最小生成树和重构树总结
c++·算法·最小生成树·重构树
阿巴~阿巴~5 小时前
冒泡排序算法
c语言·开发语言·算法·排序算法
散1126 小时前
01数据结构-交换排序
数据结构·算法
yzx9910136 小时前
Yolov模型的演变
人工智能·算法·yolo
weixin_307779137 小时前
VS Code配置MinGW64编译SQLite3库
开发语言·数据库·c++·vscode·算法
无聊的小坏坏7 小时前
拓扑排序详解:从力扣 207 题看有向图环检测
算法·leetcode·图论·拓扑学