Skip to content

Commit 3df8591

Browse files
authored
Create 1092-shortest-common-supersequence.js
1 parent 4c281f9 commit 3df8591

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

1092-shortest-common-supersequence.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @param {string} str1
3+
* @param {string} str2
4+
* @return {string}
5+
*/
6+
const shortestCommonSupersequence = function(str1, str2) {
7+
const len1 = str1.length
8+
const len2 = str2.length
9+
const mat = Array.from({ length: len1 + 1 }, () =>
10+
new Array(len2 + 1).fill(0)
11+
)
12+
for (let i = 0; i <= len1; i++) {
13+
for (let j = 0; j <= len2; j++) {
14+
if (i == 0) {
15+
mat[i][j] = str2.slice(0, j)
16+
continue
17+
}
18+
if (j == 0) {
19+
mat[i][j] = str1.slice(0, i)
20+
continue
21+
}
22+
mat[i][j] = mat[i - 1][j] + str1[i - 1]
23+
let cand1 = mat[i][j - 1] + str2[j - 1]
24+
if (cand1.length < mat[i][j].length) mat[i][j] = cand1
25+
if (str1[i - 1] === str2[j - 1]) {
26+
let cand2 = mat[i - 1][j - 1] + str1[i - 1]
27+
if (cand2.length < mat[i][j].length) mat[i][j] = cand2
28+
}
29+
}
30+
}
31+
return mat[len1][len2]
32+
}

0 commit comments

Comments
 (0)