[LintCode]Longest Common Subsequence
public class Solution {
/**
* @param A, B: Two strings.
* @return: The length of longest common subsequence of A and B.
*/
public int longestCommonSubsequence(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]; // (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;
}
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;
} else {
lcs[i][j] = Math.max(lcs[i - 1][j], lcs[i][j - 1]);
}
}
}
return lcs[m][n];
}
}