File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 1+ // https://segmentfault.com/a/1190000003914228
2+ function manacher ( s ) {
3+ // Preprocess
4+ s = '#' + s . split ( '' ) . join ( '#' ) + '#' ;
5+
6+ let RL = new Array ( s . length ) . fill ( 0 ) ;
7+ let MaxRight = 0 ;
8+ let pos = 0 ;
9+ let MaxLen = 0 ;
10+
11+ for ( let i = 0 ; i < s . length ; i ++ ) {
12+ if ( i < MaxRight ) {
13+ RL [ i ] = Math . min ( RL [ 2 * pos - i ] , MaxRight - i ) ;
14+ } else {
15+ RL [ i ] = 1 ;
16+ }
17+ // Try to expand, taking care of boundaries
18+ while ( i - RL [ i ] >= 0 && i + RL [ i ] < s . length && s [ i - RL [ i ] ] === s [ i + RL [ i ] ] ) {
19+ RL [ i ] ++ ;
20+ }
21+ // Update MaxRight and pos
22+ if ( RL [ i ] + i - 1 > MaxRight ) {
23+ MaxRight = RL [ i ] + i - 1 ;
24+ pos = i ;
25+ }
26+ // Update the length of the longest palindromic substring
27+ MaxLen = Math . max ( MaxLen , RL [ i ] ) ;
28+ }
29+ return MaxLen - 1 ;
30+ }
31+
You can’t perform that action at this time.
0 commit comments