给出两个字符串,找到最长公共子串,并返回其长度。
您在真实的面试中是否遇到过这个题? Yes
样例
给出A=“ABCD”,B=“CBCE”,返回 2
注意
子串的字符应该连续的出现在原字符串中,这与子序列有所不同。
标签
Expand
相关题目
Expand
分析:注意是子串,不是子序列,当然做法肯定也是动态规划啦,只不过转移方程需要稍微变化变化。
代码:
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 n = A.length();
int m = B.length();
vector<vector<int> > dp(n+1,vector<int>(m+1,0));
int ret = 0;
for(int i=1;i<=n;i++)
{
char c1 = A[i-1];
for(int j=1;j<=m;j++)
{
char c2 = B[j-1];
if(c1==c2)
dp[i][j] = dp[i-1][j-1]+1;
else
dp[i][j] = 0;
ret = max(ret,dp[i][j]);
}
}
return ret;
}
};