题解 | #最长公共子串#

最长公共子串

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

#include <vector>
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
        vector<vector<int>> dp(str1.length() + 1, vector<int>(str2.length() + 1, 0));
        int length = 0;
        int pos = 0;
        for(int i = 0; i < str1.length(); i++){
            for(int j = 0; j <str2.length(); j++){
                if(str1[i] == str2[j]){
                    dp[i + 1][j + 1] = dp[i][j] + 1;
                }else{
                    dp[i][j] = 0;
                }
                if(dp[i + 1][j + 1] > length){
                    length = dp[i + 1][j + 1];
                    pos = i;
                }
            }
        }
        return str1.substr(pos - length + 1, length);
    }
};

C++动态规划方法解最长公共子串

全部评论

相关推荐

07-28 16:37
门头沟学院 Java
哎,继续加油吧
ResourceUt...:能接到面试就已经是✌🏻了
腾讯一面2195人在聊
点赞 评论 收藏
分享
在等offer的火锅...:我去履历这么好,都找不到工作吗?
点赞 评论 收藏
分享
点赞 评论 收藏
分享
不多说了,看图吧
MomonKa:实际上是,机房机器有些高度,问问你身高,有没有女朋友是看你能不能猛猛加班
你最讨厌面试问你什么?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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