题解 | 最长公共子序列

最长公共子序列

https://www.nowcoder.com/questionTerminal/4727c06b9ee9446cab2e859b4bb86bb8

最长公共子序列
动态规划:

//链接:https://www.nowcoder.com/questionTerminal/4727c06b9ee9446cab2e859b4bb86bb8

#include <bits/stdc++.h>
using namespace std;

int getmaxlenght(const string &str1,const string &str2,vector<vector<int>> &dp){
    for(int i = 1; i <= str1.size(); i++){
        for(int j = 1; j <= str2.size(); j++){
            if(str1[i-1] == str2[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[str1.size()][str2.size()];
}
int main(){
    string str1,str2;
    getline(cin,str1);
    getline(cin,str2);
    vector<vector<int>> dp(str1.size()+ 1,vector<int>(str2.size()+ 1,0));
    int lenght = getmaxlenght(str1, str2, dp);

    if (lenght == 0) cout << -1;
    string ans;
    ans.resize(lenght);
    int index = lenght-1;
    int x = str1.size(), y = str2.size();
    while(index >= 0){
        if(y >= 1 && dp[x][y] == dp[x][y-1])
            y--;
        else if(x >= 1 && dp[x][y] == dp[x-1][y])
            x--;
        else{
            ans[index--] = str1[x-1];
            x--;
            y--;
        }
    }
    cout << ans;
    return 0;
}
全部评论

相关推荐

06-26 15:33
青岛工学院 Java
积极的秋田犬要冲国企:他现在邀请我明天面试
点赞 评论 收藏
分享
06-28 22:48
已编辑
广东金融学院 Java
小浪_Coding:学院本+这俩项目不是buff叠满了嘛
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务