File tree Expand file tree Collapse file tree 1 file changed +11
-12
lines changed Expand file tree Collapse file tree 1 file changed +11
-12
lines changed Original file line number Diff line number Diff line change 1
1
var longestCommonSubsequence = function ( text1 , text2 ) {
2
- let m = text1 . length ;
3
- let n = text2 . length ;
2
+ let m = text1 . length ,
3
+ n = text2 . length ,
4
+ DP = new Array ( m + 1 ) . fill ( 0 ) . map ( _ => new Array ( n + 1 ) . fill ( 0 ) ) ;
4
5
5
- let table = new Array ( m + 1 ) . fill ( ) . map ( ( ) => new Array ( n + 1 ) . fill ( 0 ) ) ;
6
-
7
- for ( let i = 1 ; i <= m ; i ++ ) {
8
- for ( let j = 1 ; j <= n ; j ++ ) {
9
- if ( text1 . charAt ( i - 1 ) !== text2 . charAt ( j - 1 ) ) {
10
- table [ i ] [ j ] = Math . max ( table [ i - 1 ] [ j ] , table [ i ] [ j - 1 ] ) ;
6
+ for ( let x = m - 1 ; x >= 0 ; x -- )
7
+ for ( let y = n - 1 ; y >= 0 ; y -- ) {
8
+ if ( text1 [ x ] === text2 [ y ] ) {
9
+ DP [ x ] [ y ] = 1 + DP [ x + 1 ] [ y + 1 ] ;
11
10
} else {
12
- table [ i ] [ j ] = table [ i - 1 ] [ j - 1 ] + 1 ;
11
+ DP [ x ] [ y ] = Math . max ( DP [ x + 1 ] [ y ] , DP [ x ] [ y + 1 ] ) ;
13
12
}
14
13
}
15
- }
16
- return table [ m ] [ n ] ;
17
- } ;
14
+
15
+ return DP [ 0 ] [ 0 ] ;
16
+ } ;
You can’t perform that action at this time.
0 commit comments