Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 4e00a0b

Browse files
committedFeb 28, 2025
Add solution #1092
1 parent c8bbb44 commit 4e00a0b

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -497,6 +497,7 @@
497497
1071|[Greatest Common Divisor of Strings](./1071-greatest-common-divisor-of-strings.js)|Easy|
498498
1079|[Letter Tile Possibilities](./1079-letter-tile-possibilities.js)|Medium|
499499
1081|[Smallest Subsequence of Distinct Characters](./1081-smallest-subsequence-of-distinct-characters.js)|Medium|
500+
1092|[Shortest Common Supersequence](./1092-shortest-common-supersequence.js)|Hard|
500501
1103|[Distribute Candies to People](./1103-distribute-candies-to-people.js)|Easy|
501502
1108|[Defanging an IP Address](./1108-defanging-an-ip-address.js)|Easy|
502503
1122|[Relative Sort Array](./1122-relative-sort-array.js)|Easy|
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* 1092. Shortest Common Supersequence
3+
* https://leetcode.com/problems/shortest-common-supersequence/
4+
* Difficulty: Hard
5+
*
6+
* Given two strings str1 and str2, return the shortest string that has both str1 and str2 as
7+
* subsequences. If there are multiple valid strings, return any of them.
8+
*
9+
* A string s is a subsequence of string t if deleting some number of characters from t (possibly
10+
* 0) results in the string s.
11+
*/
12+
13+
/**
14+
* @param {string} str1
15+
* @param {string} str2
16+
* @return {string}
17+
*/
18+
var shortestCommonSupersequence = function(str1, str2) {
19+
const dp = new Array(str1.length + 1).fill().map(() => new Array(str2.length + 1).fill(0));
20+
let result = '';
21+
22+
for (let i = 0; i <= str1.length; i++) {
23+
dp[i][0] = i;
24+
}
25+
for (let j = 0; j <= str2.length; j++) {
26+
dp[0][j] = j;
27+
}
28+
29+
for (let i = 1; i <= str1.length; i++) {
30+
for (let j = 1; j <= str2.length; j++) {
31+
dp[i][j] = str1[i-1] === str2[j-1] ? dp[i-1][j-1] + 1 : Math.min(dp[i-1][j], dp[i][j-1]) + 1;
32+
}
33+
}
34+
35+
for (let i = str1.length, j = str2.length; i > 0 || j > 0;) {
36+
if (!i) {
37+
result = str2[--j] + result;
38+
} else if (!j) {
39+
result = str1[--i] + result;
40+
} else if (str1[i-1] === str2[j-1]) {
41+
result = str1[--i] + (str2[--j], result);
42+
} else {
43+
dp[i][j] === dp[i-1][j] + 1
44+
? result = str1[--i] + result
45+
: result = str2[--j] + result;
46+
}
47+
}
48+
49+
return result;
50+
};

0 commit comments

Comments
 (0)
Please sign in to comment.