题解 | #最长公共子串#

最长公共子串

http://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
        //初始化dp矩阵值为0
        vector<vector<int>> dp(str1.size()+1, vector<int>(str2.size()+1, 0));
        int maxlen = 0;
        int index = 0;
        for(int i = 1; i<= str1.size(); i++){//i表示str1中的第i个数
            for(int j = 1 ; j <= str2.size(); j++){//j表示str2中的第j个数
                if(str1[i-1] == str2[j-1]){
                    dp[i][j] = dp[i-1][j-1] + 1;
                    if(dp[i][j] > maxlen){
                        maxlen = dp[i][j];
                        index = i-1;
                    }
                }else{
                    dp[i][j] = 0;
                }
            }
        }
        return str1.substr(index-maxlen + 1, maxlen);
    }
};
全部评论

相关推荐

07-07 12:47
门头沟学院 Java
码农索隆:竟然还真有卡体检报告的
点赞 评论 收藏
分享
06-08 22:25
门头沟学院 Java
从零开始的转码生活:这hr不会打开手机不分青红皂白给所有人群发这句话,过一会再给所有人再发一遍,这肯定会有重复的,不管,再过一会再发一遍
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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