lcs最长公共子序列 优化_2019上海交通大学计算机上机(一):最长公共子序列(LCS)...

2019上海交通大学计算机上机(一):最长公共子序列(LCS) 任何疑问、意见、建议请公众号留言或联系qq474356284

    给出两个字符串序列,求最长公共子序列(LCS) 。(改编版,原题规定两字符串长度相等,且无重复元素。)

输入格式:

    在一行分别输入两个字符串。

输出格式:

    输出两个字符串的最长公共子序列的长度。

输入样例:

abcde ace

输出样例:

3

b984984a4142211b132802e50c58beb9.gif
解决方法:

(1)代码实现:

#include 
#include 
#include 
#include 
#include 
using namespace std;
//公众号:一航代码
//LCS最长公共子序列
//递归-暴力解法
int find(string str1, string str2, int i, int j){
    //空串
    if (i == -1 || j == -1) {
        return 0;
    }
    //找到一个LCS元素,继续往前找
    if (str1[i] == str2[j]) {
        return find(str1, str2, i - 1, j - 1) + 1;
    } else {
        //哪一个串能让LCS更长就更新谁
        return max(find(str1, str2, i - 1, j), find(str1, str2, i, j - 1));
    }
    return find(str1, str2, i - 1, j - 1);
}
//使用dp Table优化
//参考:https://github.com/labuladong/fucking-algorithm/blob/master/动态规划系列/最长公共子序列.md
int longest_common_subsequence(string str1, string str2){
    int len1 = str1.size();
    int len2 = str2.size();

    vector<vector<int>> dp(len1 + 1, vector<int>(len2 + 1, 0));

    for (int i = 1; i 1; i++) {
        for (int j = 1; j 1; j++) {
            if (str1[i - 1] == str2[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[len1][len2];
}

int main(){
    string str1, str2;
    cin >> str1 >> str2;
    // cout <cout <endl;
    system("pause");
    return 0;
}

07e17a5a022eb11887731f9d1bb62689.png

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值