-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonSubsequence.java
More file actions
62 lines (54 loc) · 1.86 KB
/
LongestCommonSubsequence.java
File metadata and controls
62 lines (54 loc) · 1.86 KB
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
56
57
58
59
60
61
62
package dynamic_programming;
import data_structures.LinkedList;
public class LongestCommonSubsequence {
public static void main(String[] args) {
// Example:
System.out.println(longestCommonSubsequence("ZIEGE".toCharArray(), "TIGER".toCharArray())); // ['I', 'G', 'E']
System.out.println(longestCommonSubsequence("COVID".toCharArray(), "PARTY".toCharArray())); // []
}
public static LinkedList<Character> longestCommonSubsequence(char[] a, char[] b) {
int[][] table = new int[a.length + 1][b.length + 1];
for (int i = 0; i < a.length + 1; ++i) {
table[i][0] = 0;
}
for (int j = 0; j < b.length + 1; ++j) {
table[0][j] = 0;
}
for (int i = 1; i < table.length; ++i) {
for (int j = 1; j < table[i].length; ++j) {
table[i][j] = max(
table[i - 1][j],
table[i][j - 1],
table[i - 1][j - 1] + (a[i - 1] == b[j - 1] ? 1 : 0)
);
}
}
LinkedList<Character> solution = new LinkedList<>();
int i = a.length;
int j = b.length;
while (!(i == 0 || j == 0)) {
char charA = a[i - 1];
char charB = b[j - 1];
if (charA == charB) {
solution.addFirst(charA);
i -= 1;
j -= 1;
} else if (table[i][j] == table[i][j - 1]) {
j -= 1;
} else {
i -= 1;
}
}
return solution;
}
private static int max(int... values) {
if (values.length == 0) {
throw new IllegalArgumentException();
}
int max = values[0];
for (int i = 1; i < values.length; ++i) {
max = Math.max(max, values[i]);
}
return max;
}
}