Description
Given two strings, find the longest common subsequence (LCS).
Your code should return the length of LCS.
Clarification
What's the definition of Longest Common Subsequence?
- https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
- http://baike.baidu.com/view/2020307.htm
Example
For"ABCD"
and"EDCA"
, the_LCS_is"A"
(or"D"
,"C"
), return1
.
For"ABCD"
and"EACB"
, the_LCS_is"AC"
, return2
.
Solution
public class Solution {
/*
* @param A: A string
* @param B: A string
* @return: The length of longest common subsequence of A and B
*/
public int longestCommonSubsequence(String A, String B) {
// write your code here
if (A == null || A.length() == 0 || B == null || B.length() == 0) {
return 0;
}
int n = A.length();
int m = B.length();
int[][] dp = new int[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
if (A.charAt(i - 1) == B.charAt(j - 1)) {
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - 1] + 1);
}
}
}
return dp[n][m];
}
}