File tree Expand file tree Collapse file tree 1 file changed +15
-15
lines changed Expand file tree Collapse file tree 1 file changed +15
-15
lines changed Original file line number Diff line number Diff line change 55function countSubstrings ( s : string ) : number {
66 const str = "#" + s . split ( "" ) . join ( "#" ) + "#" ;
77 const len = str . length ;
8- const pit = new Array ( len ) . fill ( 0 ) ;
8+ const pal = new Array ( len ) . fill ( 0 ) ;
99 let center = 0 ,
10- right = 0 ,
11- result = 0 ;
10+ radius = 0 ,
11+ total = 0 ;
1212
1313 for ( let i = 0 ; i < len ; i ++ ) {
14- // If i is within the rightmost center, copy the pit value from the mirror
15- if ( i < right ) {
16- pit [ i ] = Math . min ( right - i , pit [ center * 2 - i ] ) ;
14+ // If i is within the rightmost center, copy the palindromes value from the mirror
15+ if ( i < radius ) {
16+ pal [ i ] = Math . min ( radius - i , pal [ center * 2 - i ] ) ;
1717 }
1818
1919 // Expand around i until it's not a palindrome and not over left or right
2020 while (
21- i + pit [ i ] + 1 < len &&
22- i - pit [ i ] - 1 >= 0 &&
23- str [ i + pit [ i ] + 1 ] === str [ i - pit [ i ] - 1 ]
21+ i + pal [ i ] + 1 < len &&
22+ i - pal [ i ] - 1 >= 0 &&
23+ str [ i + pal [ i ] + 1 ] === str [ i - pal [ i ] - 1 ]
2424 ) {
25- pit [ i ] ++ ;
25+ pal [ i ] ++ ;
2626 }
2727
28- // If pit value is the new rightmost center, update center and right
29- if ( i + pit [ i ] > right ) {
28+ // If palindromes value is the new rightmost center, update center and right
29+ if ( i + pal [ i ] > radius ) {
3030 center = i ;
31- right = i + pit [ i ] ;
31+ radius = i + pal [ i ] ;
3232 }
3333
3434 // Add the number of palindromes with center i to the result
35- result += Math . floor ( ( pit [ i ] + 1 ) / 2 ) ;
35+ total += Math . floor ( ( pal [ i ] + 1 ) / 2 ) ;
3636 }
3737
38- return result ;
38+ return total ;
3939}
You can’t perform that action at this time.
0 commit comments