[LintCode]Longest Common Substring
不是标准的dp
public class Solution {
/**
* @param A, B: Two string.
* @return: the length of the longest common substring.
*/
public int longestCommonSubstring(String A, String B) {
// 2015-05-19 O(n^2)
if (A == null || B == null || A.length() == 0 || B.length() == 0) {
return 0;
}
int m = A.length();
int n = B.length();
int[][] lcs = new int[m + 1][n + 1];
for (int i = 0; i <= m; i++) {
lcs[i][0] = 0;
}
for (int j = 1; j <= n; j++) {
lcs[0][j] = 0;
}
int max = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (A.charAt(i - 1) == B.charAt(j - 1)) {
lcs[i][j] = lcs[i - 1][j - 1] + 1;
max = Math.max(max, lcs[i][j]);
} else {
lcs[i][j] = 0;
}
}
}
return max;
}
}