File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string } word1
3
+ * @param {string } word2
4
+ * @return {number }
5
+ */
6
+ const longestPalindrome = function ( word1 , word2 ) {
7
+ const sz = word1 . length + word2 . length
8
+ let res = 0 ;
9
+ const dp = Array . from ( { length : sz + 1 } , ( ) => Array ( sz + 1 ) . fill ( 0 ) )
10
+ longestPalindromeSubseq ( word1 + word2 , dp ) ;
11
+ for ( let i = 0 ; i < word1 . length ; ++ i )
12
+ for ( let j = word2 . length - 1 ; j >= 0 ; -- j )
13
+ if ( word1 [ i ] == word2 [ j ] ) {
14
+ res = Math . max ( res , dp [ i ] [ word1 . length + j + 1 ] ) ;
15
+ break ;
16
+ }
17
+ return res ;
18
+
19
+ }
20
+ function longestPalindromeSubseq ( s , dp ) {
21
+ for ( let len = 1 ; len <= s . length ; ++ len )
22
+ for ( let i = 0 ; i + len <= s . length ; ++ i )
23
+ dp [ i ] [ i + len ] = s [ i ] == s [ i + len - 1 ] ?
24
+ dp [ i + 1 ] [ i + len - 1 ] + ( len == 1 ? 1 : 2 ) :
25
+ Math . max ( dp [ i ] [ i + len - 1 ] , dp [ i + 1 ] [ i + len ] ) ;
26
+ return dp [ 0 ] [ s . length ] ;
27
+ }
28
+
29
+
You can’t perform that action at this time.
0 commit comments