题解 | 最长公共子序列(二)

最长公共子序列(二)

https://www.nowcoder.com/practice/6d29638c85bb4ffd80c020fe244baf11

class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * longest common subsequence
     * @param s1 string字符串 the string
     * @param s2 string字符串 the string
     * @return string字符串
     */
    string LCS(string s1, string s2) {
        // write code here
        int len1 = s1.length(), len2 = s2.length();
        string ans;
        if (len1 == 0 || len2 == 0) {
            return "-1";
        }
        vector<vector<int>>dp(len1 + 1, vector<int>(len2 + 1, 0));
        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                dp[i][j] = 0;
            }
        }
        for (int i = 1; i <= len1; i++) {
            for (int j = 1; j <= len2; j++) {
                if (s1[i-1] == s2[j-1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        int a = len1, b = len2;
        while(dp[a][b]>0){
            if(dp[a][b]>dp[a][b-1]&&dp[a][b]>dp[a-1][b]){
                ans += s1[a-1];
                b--;
                a--;
                continue;
            }
            if(dp[a][b] == dp[a][b-1]){
                b--;
                continue;
            }
            if(dp[a][b] == dp[a-1][b]){
                a--;
                continue;
            }
        }
        reverse(ans.begin(),ans.end());
        if(ans.length()<1){
            return "-1";
        }

        return ans;
    }
};

#动态规划#
全部评论

相关推荐

03-29 14:19
门头沟学院 Java
你背过凌晨4点的八股文么:加油同学,人生的容错率很高,只是一个暑期罢了,后面还有很多机会!
点赞 评论 收藏
分享
嵌入式求职之路:可以看我经验😂,https://www.nowcoder.com/share/jump/73221730841876945
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务