题解 | #最长公共子串#

最长公共子串

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

相关推荐

程序员小白条:你是沟通了900个,不是投了900份简历,你能投900份,意味着对面都要回复你900次,你早就找到实习了,没亮点就是这样的,别局限地区,时间投的也要早,现在都要7月了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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