题解 | #最长公共子串#

最长公共子串

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);
    }
};
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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