您的位置:首页 > 其它

lintcode最长公共子串

2018-03-14 13:34 337 查看

题目:

给出两个字符串,找到最长公共子串,并返回其长度。子串的字符应该连续的出现在原字符串中,这与子序列有所不同。

样例:

给出A=“ABCD”,B=“CBCE”,返回 2

答案:

public int longestCommonSubstring(String A, String B) {
// write your code here
if(A == null || A.length() == 0 || B == null || B.length() == 0) return 0;

char[] charA = A.toCharArray(), charB = B.toCharArray();
int[][] DP = new int[charA.length + 1][charB.length + 1];
int maxLen = 0;

for(int i = 1; i <= charA.length; i++)
for(int j = 1; j <= charB.length; j++){
if(charA[i - 1] == charB[j - 1]) DP[i][j] = DP[i - 1][j - 1] + 1;

maxLen = Math.max(maxLen, DP[i][j]);
}

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