File tree Expand file tree Collapse file tree 2 files changed +83
-0
lines changed
5. Longest Palindromic Substring Expand file tree Collapse file tree 2 files changed +83
-0
lines changed Original file line number Diff line number Diff line change 1+ import { longestPalindrome } from './index' ;
2+
3+ describe ( 'longestPalindrome' , ( ) => {
4+ const testCases = [
5+ {
6+ name : 'Case 1' ,
7+ input : 'babad' ,
8+ expected : 'bab' ,
9+ } ,
10+ {
11+ name : 'Case 2' ,
12+ input : 'cbbd' ,
13+ expected : 'bb' ,
14+ } ,
15+ {
16+ name : 'Case 3' ,
17+ input : 'aacabdkacaa' ,
18+ expected : 'aca' ,
19+ } ,
20+ ] ;
21+
22+ for ( const testCase of testCases ) {
23+ test ( testCase . name , ( ) => {
24+ expect ( longestPalindrome ( testCase . input ) ) . toBe ( testCase . expected ) ;
25+ } ) ;
26+ }
27+ } ) ;
Original file line number Diff line number Diff line change 1+ // Condition of the task:
2+ // Given a string s, return the longest palindromic substring in s.
3+
4+ const processString = ( s : string ) : string => {
5+ let res = '' ;
6+
7+ for ( let i = 0 ; i < s . length ; i ++ ) {
8+ res += `#${ s [ i ] } ` ;
9+ }
10+
11+ return res + '#' ;
12+ } ;
13+
14+ const min = ( a : number , b : number ) : number => ( a < b ? a : b ) ;
15+ export const longestPalindrome = ( s : string ) : string => {
16+ const processedString = processString ( s ) ;
17+ const n = processedString . length ;
18+ const P = new Array ( n ) . fill ( 0 ) ;
19+ let C = 0 ,
20+ R = 0 ;
21+
22+ for ( let i = 0 ; i < n - 1 ; i ++ ) {
23+ const mirror = 2 * C - i ;
24+
25+ if ( i < R ) {
26+ P [ i ] = min ( R - i , P [ mirror ] ) ;
27+ } else {
28+ P [ i ] = 0 ;
29+ }
30+
31+ while (
32+ i + 1 + P [ i ] < n &&
33+ i - 1 - P [ i ] >= 0 &&
34+ processedString [ i + 1 + P [ i ] ] === processedString [ i - 1 - P [ i ] ]
35+ ) {
36+ P [ i ] ++ ;
37+ }
38+
39+ if ( i + P [ i ] > R ) {
40+ C = i ;
41+ R = i + P [ i ] ;
42+ }
43+ }
44+ let maxLen = 0 ;
45+ let centerIndex = 0 ;
46+ for ( let i = 0 ; i < n ; i ++ ) {
47+ if ( P [ i ] > maxLen ) {
48+ maxLen = P [ i ] ;
49+ centerIndex = i ;
50+ }
51+ }
52+
53+ const start = ( centerIndex - maxLen ) / 2 ;
54+ const end = start + maxLen ;
55+ return s . slice ( start , end ) ;
56+ } ;
You can’t perform that action at this time.
0 commit comments