题解 | #最长公共子串#

最长公共子串

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;
    }
};

全部评论

相关推荐

Java转测开第一人:这种就是饼 把应届当廉价劳动力用完然后丢掉
你觉得今年秋招难吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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