题解 | #最长公共子串#

最长公共子串

https://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac

记录dp数组中最大值及坐标,然后记录其左上的所有字符即可

class Solution {
public:
    string LCS(string str1, string str2) {
        string res;
        int sz1 = str1.size();
        int sz2 = str2.size();
        int _max = 0, x;
        vector<vector<int>> dp(sz1 + 1, vector<int>(sz2 + 2));
        // 动态规划
        for (int i = 1; i <= sz1; ++i) 
            for(int j = 1; j <= sz2; ++j) 
                if (str1[i - 1] == str2[j - 1]) {
                    dp[i][j] = dp[i-1][j-1] + 1;
                    if (_max < dp[i][j]) {
                        x = i - 1;  // str1 最大时坐标
                        _max = dp[i][j];
                    }
                }
                else
                    dp[i][j] = 0;
        // 输出字符
        while (_max > 0) {
            res.push_back(str1[x - _max + 1]);
            --_max;
        }
        return res;
    }
};

全部评论

相关推荐

希望被捞的猫头鹰很理智:大概率待遇低怕硕士跑路
点赞 评论 收藏
分享
01-18 09:26
已编辑
门头沟学院 Java
王桑的大offer:建议中间件那块写熟悉即可,写掌握 面试包被拷打到昏厥
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务