File tree 2 files changed +51
-0
lines changed
2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change 497
497
1071|[ Greatest Common Divisor of Strings] ( ./1071-greatest-common-divisor-of-strings.js ) |Easy|
498
498
1079|[ Letter Tile Possibilities] ( ./1079-letter-tile-possibilities.js ) |Medium|
499
499
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|
500
501
1103|[ Distribute Candies to People] ( ./1103-distribute-candies-to-people.js ) |Easy|
501
502
1108|[ Defanging an IP Address] ( ./1108-defanging-an-ip-address.js ) |Easy|
502
503
1122|[ Relative Sort Array] ( ./1122-relative-sort-array.js ) |Easy|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments