1143. Longest Common Subsequence

该博客探讨了如何使用动态规划求解两个字符串的最长公共子序列(LCS)问题。代码示例分别展示了C++和Python的实现,通过二维数组dp进行状态转移。当字符相同时,LCS长度加一,否则取之前两个状态的最大值。
摘要由CSDN通过智能技术生成

大概是最最基础的dp?
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.

不看提示还真想不出来

class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        //这题相比起第10题模式匹配温柔多了
        int l1 = text1.size();
        int l2 = text2.size();
        vector<vector<int>> dp(l1 + 1, vector<int>(l2 + 1));
        for(int i = 1; i <= l1; i++) {
            for(int j = 1; j <= l2; j++) {
                if(text1[i - 1] == text2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[l1][l2];
    }
};
class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        l1, l2 = len(text1), len(text2)
        # notice the length of array
        dp = [[0] * (l2 + 1) for _ in range(l1 + 1)]
        for i in range(1, l1 + 1):
            for j in range(1, l2 + 1):
                if text2[j - 1] == text1[i - 1]:
                    dp[i][j] = dp[i - 1][j - 1] + 1
                else:
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
        return dp[l1][l2]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值