- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestCommonSubsequence.java
More file actions
Latest commit
62 lines (54 loc) · 1.86 KB
/
Copy pathLongestCommonSubsequence.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
packagedynamic_programming;
importdata_structures.LinkedList;
publicclassLongestCommonSubsequence {
publicstaticvoidmain(String[] args) {
// Example:
System.out.println(longestCommonSubsequence("ZIEGE".toCharArray(), "TIGER".toCharArray())); // ['I', 'G', 'E']
System.out.println(longestCommonSubsequence("COVID".toCharArray(), "PARTY".toCharArray())); // []
}
publicstaticLinkedList<Character> longestCommonSubsequence(char[] a, char[] b) {
int[][] table = newint[a.length + 1][b.length + 1];
for (inti = 0; i < a.length + 1; ++i) {
table[i][0] = 0;
}
for (intj = 0; j < b.length + 1; ++j) {
table[0][j] = 0;
}
for (inti = 1; i < table.length; ++i) {
for (intj = 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 = newLinkedList<>();
inti = a.length;
intj = b.length;
while (!(i == 0 || j == 0)) {
charcharA = a[i - 1];
charcharB = b[j - 1];
if (charA == charB) {
solution.addFirst(charA);
i -= 1;
j -= 1;
} elseif (table[i][j] == table[i][j - 1]) {
j -= 1;
} else {
i -= 1;
}
}
returnsolution;
}
privatestaticintmax(int... values) {
if (values.length == 0) {
thrownewIllegalArgumentException();
}
intmax = values[0];
for (inti = 1; i < values.length; ++i) {
max = Math.max(max, values[i]);
}
returnmax;
}
}