您的位置:首页 > 其它

LintCode-最长公共子串

2015-06-25 18:49 211 查看
给出两个字符串,找到最长公共子串,并返回其长度。

您在真实的面试中是否遇到过这个题?

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: