Longest Palindrome in a String formed by concatenating its prefix and suffix | Function to check whether the String is a palindrome ; Reverse the String to compare with the original String ; Check if both are same ; Function to find the longest palindrome in a String formed by concatenating its prefix and suffix ; Length of the String ; Finding the length upto which the suffix and prefix forms a palindrome together ; Check whether the String has prefix and suffix subStrings which are palindromes . ; Removing the suffix and prefix subStrings which already forms a palindrome and storing them in separate Strings ; Check all prefix subStrings in the remaining String str ; Check if the prefix subString is a palindrome ; If the prefix subString is a palindrome then check if it is of maximum length so far ; Check all the suffix subStrings in the remaining String str ; Check if the suffix subString is a palindrome ; If the suffix subString is a palindrome then check if it is of maximum length so far ; Combining all the thee parts of the answer ; Driver code
function isPalindrome ( r ) { let p = r ; p = reverse ( p ) ; return ( r == ( p ) ) ; } function PrefixSuffixPalindrome ( str ) { let n = str . length , len = 0 ; for ( let i = 0 ; i < n / 2 ; i ++ ) { if ( str [ i ] != str [ n - i - 1 ] ) { len = i ; break ; } } let prefix = " " , suffix = " " ; let midPal = " " ; prefix = str . substring ( 0 , len ) ; suffix = str . substring ( n - len ) ; str = str . substring ( len , ( n - 2 * len ) + len ) ; for ( let i = 1 ; i <= str . length ; i ++ ) { let y = str . substring ( 0 , i ) ; if ( isPalindrome ( y ) ) { if ( midPal . length < y . length ) { midPal = y ; } } } for ( let i = 1 ; i <= str . length ; i ++ ) { let y = str . substring ( str . length - i ) ; if ( isPalindrome ( y ) ) { if ( midPal . length < y . length ) { midPal = y ; } } } let answer = prefix + midPal + suffix ; return answer ; } function reverse ( input ) { let a = input . split ( " " ) ; let l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { let temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return ( a ) . join ( " " ) ; } let str = " " ; document . write ( PrefixSuffixPalindrome ( str ) ) ;