Skip to content

Commit 887025a

Browse files
Lintcode/src/chapter5_DynamicProgrammingII/
1 parent e4577da commit 887025a

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package chapter5_DynamicProgrammingII;
2+
/**Given two strings, find the longest common subsequence (LCS).
3+
4+
Your code should return the length of LCS.
5+
Example
6+
For "ABCD" and "EDCA", the LCS is "A" (or "D", "C"), return 1.
7+
8+
For "ABCD" and "EACB", the LCS is "AC", return 2.
9+
*/
10+
public class LongestCommonSubsequence {
11+
12+
/**
13+
* @param A, B: Two strings.
14+
* @return: The length of longest common subsequence of A and B.
15+
*/
16+
public int longestCommonSubsequence(String A, String B) {
17+
// write your code here
18+
int m = A.length(), n = B.length();
19+
int[][] dp = new int[m+1][n+1];
20+
21+
for(int i = 0; i <= m; i++) dp[i][0] = 0;
22+
23+
for(int j = 0; j <= n; j++) dp[0][j] = 0;
24+
25+
for(int i = 1; i <= m; i++){
26+
for(int j = 1; j <= n; j++){
27+
int match = 0;
28+
if(A.charAt(i-1) == B.charAt(j-1)) match = 1;
29+
dp[i][j] = Math.max(Math.max(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]+match);
30+
}
31+
}
32+
33+
return dp[m][n];
34+
}
35+
36+
}

0 commit comments

Comments
 (0)