-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathLongestCommonSubsequence.java
55 lines (42 loc) Β· 1.38 KB
/
LongestCommonSubsequence.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package section19_DynamicProgramming;
public class LongestCommonSubsequence {
public static void main(String[] args) {
String str1 = "abbg";
String str2 = "agbg";
System.out.println(lcs(str1, str2));
System.out.println(lcsIterative(str1, str2));
}
public static int lcs(String str1, String str2) {
if (str1.length() == 0 || str2.length() == 0)
return 0;
int count = 0;
String restString1 = str1.substring(1);
String restString2 = str2.substring(1);
if (str1.charAt(0) == str2.charAt( 0)) {
count = 1 + lcs(restString1, restString2);
} else {
int factor1 = lcs(str1, restString2);
int factor2 = lcs(restString1, str2);
count = Math.max(factor1, factor2);
}
return count;
}
// O(nm) Time, where n is length of str1, m is length of str2
public static int lcsIterative(String str1, String str2) {
int[][] storage = new int[str1.length() + 1][str2.length() + 1];
for (int row = storage.length - 1; row >= 0; row--) {
for (int col = storage.length - 1; col >= 0; col--) {
String s1 = str1.substring(row);
String s2 = str2.substring(col);
if (s1.length() == 0 || s2.length() == 0)
storage[row][col] = 0;
else if (s1.charAt(0) == s2.charAt(0)) {
storage[row][col] = 1 + storage[row + 1][col + 1];
} else {
storage[row][col] = Math.max(storage[row][col + 1], storage[row + 1][col]);
}
}
}
return storage[0][0];
}
}