lintcode 最长公共子串

作者: yzawyx0220 | 来源:发表于2017-01-13 11:09 被阅读86次

    给出两个字符串,找到最长公共子串,并返回其长度。
    注意事项
    子串的字符应该连续的出现在原字符串中,这与子序列有所不同。
    样例
    给出A=“ABCD”,B=“CBCE”,返回 2
    题目链接:http://www.lintcode.com/zh-cn/problem/longest-common-substring/
    最长公共子串和最长公共子序列不同地方在于子串必须连续的,而子序列可以不连续。这里依然建立二维数组,dp[i][j]表示的是A的前i段和B的前j段包括A[i-1]和B[j-1]在内的公共子串,因此,如果A[i-1]不等于B[j-1],则dp[i][j]等于0。

    class Solution {
    public:    
        /**
         * @param A, B: Two string.
         * @return: the length of the longest common substring.
         */
        int longestCommonSubstring(string &A, string &B) {
            // write your code here
            int m = A.size(),n = B.size();
            vector<vector<int> > dp(m + 1,vector<int>(n + 1,0));
            int res = 0;
            for (int i = 1;i <= m;i++) {
                for (int j = 1;j <= n ;j++) {
                    if (A[i - 1] == B[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
                    else dp[i][j] = 0;
                    res = max(res,dp[i][j]);
                }
            }
            return res;
        }
    };
    
    

    相关文章

      网友评论

        本文标题:lintcode 最长公共子串

        本文链接:https://www.haomeiwen.com/subject/tqxsbttx.html