-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.sequence.lcs.js
More file actions
73 lines (65 loc) · 1.75 KB
/
string.sequence.lcs.js
File metadata and controls
73 lines (65 loc) · 1.75 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
63
64
65
66
67
68
69
70
71
72
73
/*
* @title: Longest Common SubSequence
* @description: lcs in two strings
* @author: Thorsten Kober
* @email: [email protected]
*/
// time: O(n^2);
function lcs(str1, str2, index1, index2) {
if (index1 === 0 || index2 === 0) return 0;
if (str1[index1 - 1] === str2[index2 - 1]) {
return 1 + lcs(str1, str2, index1 - 1, index2 - 1);
}
return Math.max(
lcs(str1, str2, index1, index2 - 1),
lcs(str1, str2, index1 - 1, index2),
);
}
function print(str1, str2, result) {
let index1 = str1.length;
let index2 = str2.length;
const chars = {};
while (index1 > 0 && index2 > 0) {
if (result[index1 - 1] === result[index2 - 1]) {
const current = str1[index1 - 1];
chars[current] = true;
index1--;
index2--;
} else if (result[index1 - 1][index2] > result[index1][index2 - 1]) {
index1--;
} else {
index2--;
}
}
console.log(Object.keys(chars).reverse());
}
// time: O(mn);
function lcs2(str1, str2) {
const result = [];
for (let i = 0; i <= str1.length; i++) {
result[i] = [];
for (let j = 0; j <= str2.length; j++) {
result[i][j] = 0;
}
}
for (let i = 1; i <= str1.length; i++) {
for (let j = 1; j <= str2.length; j++) {
if (str1[i - 1] === str2[j - 1]) {
result[i][j] = result[i - 1][j - 1] + 1;
} else {
result[i][j] = Math.max(result[i - 1][j], result[i][j - 1]);
}
}
}
print(str1, str2, result);
return result[str1.length][str2.length];
}
// npx jest algorithms/string/string.sequence.lcs.js
test('lcs()', () => {
const str1 = 'AGGTAB';
const str2 = 'GXTXAYB';
const index1 = str1.length;
const index2 = str2.length;
expect(lcs(str1, str2, index1, index2)).toEqual(4);
expect(lcs2(str1, str2)).toEqual(4);
});