Given two strings, find the longest common subsequence (LCS).
Your code should return the length of LCS.
Example
For "ABCD"
and "EDCA"
, the LCS is "A"
(or "D"
, "C"
), return 1
.
For "ABCD"
and "EACB"
, the LCS is "AC"
, return 2
.
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) {
if(A.length() == 0 || B.length() == 0) return 0;
int[][] res = new int[A.length()][B.length()];
res[0][0] = A.charAt(0) == B.charAt(0) ? 1 : 0;
for(int i = 1; i < A.length(); i++) res[i][0] = A.charAt(i) == B.charAt(0) ? 1 : 0;
for(int j = 1; j < B.length(); j++) res[0][j] = B.charAt(j) == A.charAt(0) ? 1 : 0;
for(int i = 1; i < A.length(); i++) {
for(int j = 1; j < B.length(); j++) {
if(A.charAt(i) == B.charAt(j)) {
res[i][j] = res[i - 1][j - 1] + 1;
} else {
res[i][j] = Math.max(res[i - 1][j], res[i][j - 1]);
}
}
}
return res[A.length() - 1][B.length() - 1];
}
}