Skip to content

Commit 0f59249

Browse files
author
piggy1991
committed
llint
1 parent 03fcafa commit 0f59249

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package Algorithms.lintcode.dp;
2+
3+
public class LongestCommonSubstring {
4+
/**
5+
* @param A, B: Two string.
6+
* @return: the length of the longest common substring.
7+
*/
8+
public int longestCommonSubstring(String A, String B) {
9+
// write your code here
10+
if (A == null || B == null) {
11+
return 0;
12+
}
13+
14+
int lenA = A.length();
15+
int lenB = B.length();
16+
17+
// bug 1: use error init.
18+
int[][] D = new int[lenA + 1][lenB + 1];
19+
20+
int max = 0;
21+
22+
// BUG 2: should use <= instead of <
23+
for (int i = 0; i <= lenA; i++) {
24+
for (int j = 0; j <= lenB; j++) {
25+
if (i == 0 || j == 0) {
26+
D[i][j] = 0;
27+
} else {
28+
if (A.charAt(i - 1) == B.charAt(j - 1)) {
29+
D[i][j] = D[i - 1][j - 1] + 1;
30+
} else {
31+
D[i][j] = 0;
32+
}
33+
}
34+
35+
max = Math.max(max, D[i][j]);
36+
}
37+
}
38+
39+
return max;
40+
}
41+
}

0 commit comments

Comments
 (0)