File tree Expand file tree Collapse file tree 2 files changed +46
-0
lines changed
algorithms/JavaScript/LongestCommonSubsequence Expand file tree Collapse file tree 2 files changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ const { lcs} = require ( '../index' ) ;
2
+
3
+ describe ( "LongestCommonSubsequence" , ( ) => {
4
+
5
+ it ( "should return 0 if length is 0" , ( ) => {
6
+ expect ( lcs ( "" , "A" ) ) . toEqual ( 0 ) ;
7
+ } ) ;
8
+
9
+ it ( "should return 0 if the string is undefined" , ( ) => {
10
+ expect ( lcs ( "A" ) ) . toEqual ( 0 ) ;
11
+ } ) ;
12
+
13
+ it ( "should return 0 if the string is undefined" , ( ) => {
14
+ expect ( lcs ( "A" , null ) ) . toEqual ( 0 ) ;
15
+ } ) ;
16
+
17
+ it ( "should return correct value for valid strings" , ( ) => {
18
+ expect ( lcs ( "AGGTAB" , "GXTXAYB" ) ) . toEqual ( 4 ) ;
19
+ } ) ;
20
+ } ) ;
Original file line number Diff line number Diff line change
1
+ const lcs = ( string1 , string2 ) => {
2
+
3
+ if ( ! string1 || ! string2 ) return 0 ;
4
+
5
+ const string1Array = string1 . split ( '' ) ;
6
+ const string2Array = string2 . split ( '' ) ;
7
+
8
+ const dpArray = [ ] ;
9
+
10
+ string1Array . forEach ( ( ) => {
11
+ dpArray . push ( [ ] ) ;
12
+ } ) ;
13
+
14
+ for ( let i = 0 ; i < string1Array . length ; i += 1 ) {
15
+ for ( let j = 0 ; j < string2Array . length ; j += 1 ) {
16
+ if ( string1Array [ i ] === string2Array [ j ] ) {
17
+ dpArray [ i ] [ j ] = 1 + ( dpArray [ i - 1 ] ?. [ j - 1 ] ? dpArray [ i - 1 ] [ j - 1 ] : 0 )
18
+ } else {
19
+ dpArray [ i ] [ j ] = Math . max ( dpArray [ i - 1 ] ?. [ j ] ? dpArray [ i - 1 ] [ j ] : 0 , dpArray [ i ] ?. [ j - 1 ] ? dpArray [ i ] [ j - 1 ] : 0 )
20
+ }
21
+ }
22
+ }
23
+ return dpArray [ string1Array . length - 1 ] [ string2Array . length - 1 ]
24
+ }
25
+
26
+ module . exports = { lcs} ;
You can’t perform that action at this time.
0 commit comments