Longest palindromic string possible after removal of a substring | Function to find the longest palindrome from the start of the String using KMP match ; Append S ( reverse of C ) to C ; Use KMP algorithm ; Function to return longest palindromic String possible from the given String after removal of any subString ; Initialize three Strings A , B AND F ; Loop to find longest subStrings from both ends which are reverse of each other ; Proceed to third step of our approach ; Remove the subStrings A and B ; Find the longest palindromic subString from beginning of C ; Find the longest palindromic subString from end of C ; Store the maximum of D and E in F ; Find the readonly answer ; Driver Code
function findPalindrome ( C ) { var S = C ; S = reverse ( S ) ; C = C + " " + S ; var n = C . length ; var longestPalindrome = new Array ( n ) . fill ( 0 ) ; longestPalindrome [ 0 ] = 0 ; var len = 0 ; var i = 1 ; while ( i < n ) { if ( C [ i ] === C [ len ] ) { len ++ ; longestPalindrome [ i ] = len ; i ++ ; } else { if ( len !== 0 ) { len = longestPalindrome [ len - 1 ] ; } else { longestPalindrome [ i ] = 0 ; i ++ ; } } } var ans = C . substring ( 0 , longestPalindrome [ n - 1 ] ) ; return ans ; } function findAns ( s ) { var A = " " ; var B = " " ; var F = " " ; var i = 0 ; var j = s . length - 1 ; var len = s . length ; while ( i < j && s [ i ] === s [ j ] ) { i = i + 1 ; j = j - 1 ; } if ( i > 0 ) { A = s . substring ( 0 , i ) ; B = s . substring ( len - i , len ) ; } if ( len > 2 * i ) { var C = s . substring ( i , i + ( s . length - 2 * i ) ) ; var D = findPalindrome ( C ) ; C = reverse ( C ) ; var E = findPalindrome ( C ) ; if ( D . length > E . length ) { F = D ; } else { F = E ; } } var answer = A + F + B ; return answer ; } function reverse ( input ) { var a = input . split ( " " ) ; var r = a . length - 1 ; for ( var l = 0 ; l < r ; l ++ , r -- ) { var temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return a . join ( " " ) ; } var str = " " ; document . write ( findAns ( str ) ) ;