Rearrange string to obtain Longest Palindromic Substring | Function to rearrange the string to get the longest palindromic substring ; Stores the length of str ; Store the count of occurrence of each character ; Traverse the string , str ; Count occurrence of each character ; Store the left half of the longest palindromic substring ; Store the right half of the longest palindromic substring ; Traverse the array , hash [ ] ; Append half of the characters to res1 ; Append half of the characters to res2 ; Reverse string res2 to make res1 + res2 palindrome ; Store the remaining characters ; Check If any odd character appended to the middle of the resultant string or not ; Append all the character which occurs odd number of times ; If count of occurrence of characters is odd ; Driver Code
function longestPalinSub ( str ) { var N = str . length ; var hash = Array ( 256 ) . fill ( 0 ) ; for ( var i = 0 ; i < N ; i ++ ) { hash [ str [ i ] . charCodeAt ( 0 ) ] ++ ; } var res1 = [ ] ; var res2 = [ ] ; for ( var i = 0 ; i < 256 ; i ++ ) { for ( var j = 0 ; j < parseInt ( hash [ i ] / 2 ) ; j ++ ) { res1 . push ( String . fromCharCode ( i ) ) ; } for ( var j = parseInt ( ( hash [ i ] + 1 ) / 2 ) ; j < hash [ i ] ; j ++ ) { res2 . push ( String . fromCharCode ( i ) ) ; } } res2 = res2 . reverse ( ) ; var res3 = [ ] ; var f = false ; for ( var i = 0 ; i < 256 ; i ++ ) { if ( hash [ i ] % 2 ) { if ( ! f ) { res1 . push ( String . fromCharCode ( i ) ) ; f = true ; } else { res3 . push ( String . fromCharCode ( i ) ) ; } } } return ( res1 . join ( ' ' ) + res2 . join ( ' ' ) + res3 . join ( ' ' ) ) ; } var str = " " ; document . write ( longestPalinSub ( str ) ) ;