-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1092 Shortest Common Supersequence.js
More file actions
64 lines (55 loc) · 1.35 KB
/
1092 Shortest Common Supersequence.js
File metadata and controls
64 lines (55 loc) · 1.35 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
/**
* @param {string} str1
* @param {string} str2
* @return {string}
*/
var shortestCommonSupersequence = function (str1, str2) {
if (str1 === str2) return str1;
const m = str1.length;
const n = str2.length;
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(-1));
for (let i = 0; i <= m; i++) {
dp[i][0] = 0;
}
for (let j = 0; j <= n; j++) {
dp[0][j] = 0;
}
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
// match
if (str1[i - 1] === str2[j - 1]) {
dp[i][j] = 1 + dp[i - 1][j - 1];
} else {
// not match
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
// backtracking
let i = m;
let j = n;
let str = [];
while (i > 0 && j > 0) {
if (str1[i - 1] === str2[j - 1]) {
str.unshift(str1[i - 1]);
i--;
j--;
} else if (dp[i - 1][j] > dp[i][j - 1]) {
str.unshift(str1[i - 1]);
i--;
} else {
str.unshift(str2[j - 1]);
j--;
}
}
// adding remaining characters
while (i > 0) {
str.unshift(str1[i - 1]);
i--;
}
while (j > 0) {
str.unshift(str2[j - 1]);
j--;
}
return str.join('');
};