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

最长公共子序列(二)

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

#include <iterator>
#include <string>
#include <vector>
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
        if (s1.empty() || s2.empty()) {
    return "-1";
}

        int n = s1.size();
        int m = s2.size();
        s1 = " " + s1;
        s2 = " " + s2;



        vector<vector<int>> dp(n + 1, vector<int> (m + 1,0));
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (s1[i] == s2[j]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;

                } else {
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
                }

            }
        }
        if (dp[n][m] == 0) {
            return "-1";
        }
        string ret;
        //咋瓦鲁多,时空回溯~
        int i = n;
        int j = m;
        while (i > 0 && j > 0) 
        {
            if (s1[i] == s2[j]) 
            {
                ret+=s1[i];
                i--;
                j--;
            } 
            else 
            {
                if (dp[i - 1][j] > dp[i][j - 1]) 
                {
                    i--;
                }
                else 
                {
                    j--;
                }
            }
        }
        reverse(ret.begin(),ret.end());
        return ret;

    }
};

全部评论

相关推荐

群星之怒:不是哥们,你就不好奇瘫痪三十年的老植物人是啥样的吗?
点赞 评论 收藏
分享
Aaso:挺好的,早挂早超生
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务