Leetcode: 最长公共子序列(Longest Common Subsequence)(C++)

17 篇文章 0 订阅
17 篇文章 0 订阅

Given two strings text1 and text2, return the length of their longest common subsequence.

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. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings.

If there is no common subsequence, return 0.

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 <= 1000
  • 1 <= text2.length <= 1000
  • The input strings consist of lowercase English characters only.

给定两个字符串text1和text2,返回它们最长的公共子序列的长度。

字符串的子序列是从原始字符串生成的新字符串,其中删除了一些字符(可以是一个字符),而不会更改其余字符的相对顺序。 (例如,“ ace”是“ abcde”的子序列,而“ aec”则不是)。 两个字符串的公共子序列是两个字符串共有的子序列。

如果没有公共子序列,则返回0。


这里一开始没看懂题目,试了几次,才发现意思是text1和text2的子序列是可以跳过它们任何的字符,但是必须按顺序。

比如text1="abcd" text2="dadc" result="ac" 输出2

题目乍一看很简单,实际上加了刚刚我发现的限制以后,就不能简单的判断了。这里用暴力法能做,但是会超时,所以只能动态规划,想到这点应该就不难了。

class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        int t1_len = text1.length(), t2_len = text2.length();
        if(!(t1_len & t2_len))
            return 0;
        vector<int> buffer(t2_len, 0);
        vector<vector<int>> result_table(t1_len, buffer);
        for(int i2 = 0; i2 < text2.length(); i2++){
            for(int i1 = 0; i1 < text1.length(); i1++){
                if(text1[i1] == text2[i2]){
                    if(i1 > 0 && i2 > 0)
                        result_table[i1][i2] = result_table[i1 - 1][i2 - 1] + 1;
                    else
                        result_table[i1][i2] = 1;
                }
                else{
                    if(i1 > 0 && i2 > 0)
                        result_table[i1][i2] = max(result_table[i1 - 1][i2], result_table[i1][i2 - 1]);
                    else if(i1 > 0)
                        result_table[i1][i2] = result_table[i1 - 1][i2];
                    else if(i2 > 0)
                        result_table[i1][i2] = result_table[i1][i2 - 1];
                    else
                        result_table[i1][i2] = 0;
                }
            }
        }
        return result_table[t1_len - 1][t2_len - 1];
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值