题解 | #最长公共子串#

最长公共子串

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

1.动态规划,啥也不是

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

相关推荐

屌丝逆袭咸鱼计划:心态摆好,man,晚点找早点找到最后都是为了提升自己好进正职,努力提升自己才是最关键的😤难道说现在找不到找的太晚了就炸了可以鸡鸡了吗😤早实习晚实习不都是为了以后多积累,大四学长有的秋招进的也不妨碍有的春招进,人生就这样
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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