File tree 1 file changed +32
-0
lines changed
1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments