题解 | #最长公共子串#

最长公共子串

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) {
        int n = str1.size();
        int m = str2.size();
        vector<vector<int>> dp(n+1,vector<int>(m+1,0));
        int max = 0,index = -1;
        for(int i = 1;i <= n;i++){
            for(int j = 1;j <= m;j++){
                if(str1[i - 1] == str2[j - 1]){
                    dp[i][j] = dp[i-1][j-1] + 1;
                    if(max < dp[i][j]){
                    max = dp[i][j];
                    index = i;
                    }
                }
            }
        }
        return str1.substr(index - max,max);
    }
};
全部评论

相关推荐

10-28 17:30
已编辑
华东交通大学 Java
iori2333:这太正常了 我字节面了四五轮 没有一次是在官网投递 都是hr主动捞
秋招笔试记录
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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