每日一题 day 56(DP topic)

本文探讨了LeetCode问题1143中寻找两个字符串最长公共子序列的解决方案,重点介绍了动态规划的实现方法,并对比了一种更简洁的代码版本。错误的尝试也被提及,以帮助读者理解最佳实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

problem

1143. 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.

approach DP

class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        vector<vector<int>> dp(text1.size()+1, vector<int>(text2.size()+1, 0));
        for(int i=0; i<text1.size(); i++){
            for(int j=0; j<text2.size(); j++){
                if(text1[i] == text2[j]){
                    dp[i+1][j+1] = dp[i][j] + 1;
                }else dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j]);
            }
        }
        return dp[text1.size()][text2.size()];
    }
};

approach shorter code

class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        vector<vector<int>> dp(2, vector<int>(text2.size()+1, 0));
        for(int i=0; i<text1.size(); i++)
            for(int j=0; j<text2.size(); j++)
                dp[(i+1)%2][j+1] = text1[i] == text2[j] ? dp[i%2][j] + 1 : max(dp[i%2][j+1], dp[(i+1)%2][j]);
        return dp[text1.size()%2][text2.size()];
    }
};

在这里插入图片描述
在这里插入图片描述

wrong approach

class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        string small, big;
        if(text1.size() > text2.size()){
            small = text2, big = text1;
        }else{
            small = text1, big = text2;
        }
        
        int j = 0, pre = 0 , cnt = 0;
        for(auto x : small){
            for(; j<big.size(); j++){
                if(big[j] == x){
                    cnt++;
                    pre = j + 1;
                    break;
                }
            }
            if(j == big.size()){// not found
                j = pre;
            }
        }
        return cnt;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值