Count of palindromes that can be obtained by concatenating equal length prefix and substrings | Function to calculate the number of palindromes ; Calculation of Z - array ; Calculation of sigma ( Z [ i ] + 1 ) ; Return the count ; Given String
function countPalindromes ( S ) { var N = S . length ; var Z = Array ( N ) . fill ( 0 ) ; var l = 0 , r = 0 ; for ( var i = 1 ; i < N ; i ++ ) { if ( i <= r ) Z [ i ] = Math . min ( r - i + 1 , Z [ i - l ] ) ; while ( i + Z [ i ] < N && S [ Z [ i ] ] == S [ i + Z [ i ] ] ) { Z [ i ] ++ ; } if ( i + Z [ i ] - 1 > r ) { l = i ; r = i + Z [ i ] - 1 ; } } var sum = 0 ; for ( var i = 0 ; i < Z . length ; i ++ ) { sum += Z [ i ] + 1 ; } return sum ; } var S = " " ; document . write ( countPalindromes ( S ) ) ;