LintCode-最长公共子串
给出两个字符串,找到最长公共子串。并返回其长度。
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;
}
};
浙公网安备 33010602011771号