您的位置:首页 > 其它

lintcode-medium-Longest Common Substring

2016-03-26 06:43 302 查看
Given two strings, find the longest common substring.

Return the length of it.

Example

Given A =
"ABCD"
, B =
"CBCE"
, return
2
.

Challenge

O(n x m) time and memory.

这道题和longest common subsequence差不多,也是动态规划,状态转移稍有区别:

一个二维int数组记录A前i个字符和B前j个字符的longest common subsequence

当A的第i - 1个字符和B的第j - 1个字符不相等时,dp[i][j]为之前的情况中数值最大的,即dp[i][j - 1]和dp[i - 1][j]中较大的

当两个字符相等时,必须从后往前数包括这两个字符的substring的长度是否大于dp[i][j - 1]和dp[i - 1][j],大于的话更新一下dp[i][j],否则和不相等时一样

public class Solution {
/**
* @param A, B: Two string.
* @return: the length of the longest common substring.
*/
public int longestCommonSubstring(String A, String B) {
// write your code here

if(A == null || A.length() == 0 || B == null || B.length() == 0)
return 0;

int m = A.length();
int n = B.length();
int[][] dp = new int[m + 1][n + 1];

dp[0][0] = 0;
for(int i = 1; i <= m; i++)
dp[i][0] = 0;
for(int i = 1; i <= n; i++)
dp[0][i] = 0;

for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
if(A.charAt(i - 1) != B.charAt(j - 1)){
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
else{
int len = 0;
while(i - len - 1 >= 0  && j - 1 - len >= 0 && A.charAt(i - 1 - len) == B.charAt(j - 1 - len))
len++;

dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
dp[i][j] = Math.max(dp[i][j], len);
}

}
}

return dp[m]
;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: