File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
longest-palindromic-substring Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time complexity: O(n^2)
2+ // Space complexity: O(n^2)
3+
4+ /**
5+ * @param {string } s
6+ * @return {string }
7+ */
8+ var longestPalindrome = function ( s ) {
9+ const dp = Array . from ( { length : s . length } , ( ) =>
10+ Array . from ( { length : s . length } , ( ) => false )
11+ ) ;
12+
13+ let answer = "" ;
14+ let start = 0 ;
15+ let end = 0 ;
16+
17+ const update = ( i , j ) => {
18+ const newLen = Math . abs ( i - j ) + 1 ;
19+
20+ if ( newLen > end - start + 1 ) {
21+ start = i ;
22+ end = j ;
23+ }
24+ } ;
25+
26+ for ( let i = s . length - 1 ; i >= 0 ; i -- ) {
27+ for ( let j = i ; j < s . length ; j ++ ) {
28+ if ( i === j ) {
29+ dp [ i ] [ j ] = true ;
30+ update ( i , j ) ;
31+ continue ;
32+ }
33+
34+ if ( i + 1 === j ) {
35+ if ( s [ i ] === s [ j ] ) {
36+ dp [ i ] [ j ] = true ;
37+ update ( i , j ) ;
38+ }
39+
40+ continue ;
41+ }
42+
43+ if ( dp [ i + 1 ] [ j - 1 ] && s [ i ] === s [ j ] ) {
44+ dp [ i ] [ j ] = true ;
45+ update ( i , j ) ;
46+ }
47+ }
48+ }
49+
50+ return s . slice ( start , end + 1 ) ;
51+ } ;
You can’t perform that action at this time.
0 commit comments