File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ LeetCode -> https://leetcode.com/problems/longest-palindromic-subsequence/
3+
4+ Given a string s, find the longest palindromic subsequence's length in s.
5+ You may assume that the maximum length of s is 1000.
6+
7+ */
8+
9+ const longestPalindromeSubsequence = function ( s ) {
10+ const n = s . length
11+
12+ const dp = new Array ( n ) . fill ( 0 ) . map ( item => new Array ( n ) . fill ( 0 ) . map ( item => 0 ) )
13+
14+ // fill predefined for single character
15+ for ( let i = 0 ; i < n ; i ++ ) {
16+ dp [ i ] [ i ] = 1
17+ }
18+
19+ for ( let i = 1 ; i < n ; i ++ ) {
20+ for ( let j = 0 ; j < n - i ; j ++ ) {
21+ const col = j + i
22+ if ( s [ j ] === s [ col ] ) {
23+ dp [ j ] [ col ] = 2 + dp [ j + 1 ] [ col - 1 ]
24+ } else {
25+ dp [ j ] [ col ] = Math . max ( dp [ j ] [ col - 1 ] , dp [ j + 1 ] [ col ] )
26+ }
27+ }
28+ }
29+
30+ return dp [ 0 ] [ n - 1 ]
31+ }
32+
33+ const main = ( ) => {
34+ console . log ( longestPalindromeSubsequence ( 'bbbab' ) ) // 4
35+ console . log ( longestPalindromeSubsequence ( 'axbya' ) ) // 3
36+ console . log ( longestPalindromeSubsequence ( 'racexyzcxar' ) ) // 7
37+ }
38+
39+ main ( )
You can’t perform that action at this time.
0 commit comments