题解 | #最长公共子串#

最长公共子串

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

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * longest common substring
     * @param str1 string字符串 the string
     * @param str2 string字符串 the string
     * @return string字符串
     */
    string LCS(string str1, string str2) {
        // write code here
        if (str1.empty() || str2.empty()) {
            return "";
        }
        int m = str1.length();
        int n = str2.length();
        std::vector<std::vector<int>> dp(m, std::vector<int>(n, 0));
        if (str1[0] == str2[0]) {
            dp[0][0] = 1;
        }
        int max_length = 0;
        int pos = 0;
        for (int i = 1; i < str1.size(); i++) {
            for (int j = 1; j < str2.size(); j++) {
                if (str1[i] == str2[j]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = 0;
                }
                if (dp[i][j] > max_length) {
                    max_length = dp[i][j];
                    pos = i;
                }
            }
        }

        return str1.substr(pos - max_length + 1, max_length);
    }
};

全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务