Longest Common Substring,longestsubstring
分享于 点击 24384 次 点评:22
Longest Common Substring,longestsubstring
Given two strings, find the longest common substring.
Return the length of it.
Notice
The characters in substring should occur continuously in original string. This is different with subsequence.
Have you met this question in a real interview? Yes ExampleGiven A = "ABCD"
, B
= "CBCE"
, return 2
.
非常经典的动态规划的题。然而转移方程特别好想到。使用的DP数组应该是二维的数组,因为子问题是m[i, j], A的子串i~len(A), B的子串j~len(B)一共能够出现的最长子串是多少。转移方程也比subsequence的要简单。如果当前位置的字符不一样,那么说明在当前的i, j 的匹配过程中,结果是不存在的,那么将dp[i][j] 设置成0。否则的话对角线元素+1.
子问题的描述我会选择重新解释一下
代码:
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 [][] dp = new int [A.length()][B.length()];
//init
int max = 0;
for(int i=0;i<A.length();i++){
if(A.charAt(i) == B.charAt(0)){
dp[i][0] = 1;
max = 1;
}
}
for(int i=0;i<B.length();i++){
if(A.charAt(0) == B.charAt(i)){
dp[0][i] = 1;
max = 1;
}
}
for(int i=1;i<A.length();i++){
for(int j=1;j<B.length();j++){
if(A.charAt(i) == B.charAt(j)){
dp[i][j] = dp[i-1][j-1] +1;
max = Math.max(max, dp[i][j]);
}else{
dp[i][j] = 0;
}
}
}
return max;
}
相关文章
- 暂无相关文章
用户点评