lintcode-最长公共子串-79

给出两个字符串,找到最长公共子串,并返回其长度。

样例

给出A=“ABCD”,B=“CBCE”,返回 2

注意

子串的字符应该连续的出现在原字符串中,这与子序列有所不同。

class Solution {
public:    
    
    int longestCommonSubstring(string &A, string &B) {
        if(A.empty()||B.empty())
            return 0;
        int dp[A.length()+1][B.length()+1];   
        int maxp=0;
        memset(dp,0,sizeof(dp));
        for(int i=1;i<A.length()+1;++i){
            for(int j=1;j<B.length()+1;++j){
                if(A[i-1]==B[j-1])
                    dp[i][j]=dp[i-1][j-1]+1;
                else
                    dp[i][j]=0;
                maxp=max(maxp,dp[i][j]);    
            }
        }
        return maxp;
    }
};



你可能感兴趣的:(lintcode-最长公共子串-79)