原题网址:https://www.lintcode.com/problem/longest-common-substring/description
给出两个字符串,找到最长公共子串,并返回其长度。
子串的字符应该连续的出现在原字符串中,这与子序列有所不同。
给出A=“ABCD”,B=“CBCE”,返回 2
O(n x m) time and memory.
class Solution {
public:
/**
* @param A: A string
* @param B: A string
* @return: the length of the longest common substring.
*/
int longestCommonSubstring(string &A, string &B) {
// write your code here
int n1=A.size(),n2=B.size();
if (n1==0||n2==0)
{
return 0;
}
vector<vector<int>> dp(n1+1,vector<int>(n2+1,0));
int maxl=-1;
for (int i=1;i<=n1;i++)
{
for (int j=1;j<=n2;j++)
{
if (A[i-1]==B[j-1])
{
dp[i][j]=dp[i-1][j-1]+1;
}
maxl=max(maxl,dp[i][j]);
}
}
return maxl;
}
};
原文:https://www.cnblogs.com/Tang-tangt/p/9307477.html