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
def isPalindrome ( r ) : NEW_LINE INDENT p = r NEW_LINE p = " " . join ( reversed ( p ) ) NEW_LINE return ( r == p ) NEW_LINE DEDENT def PrefixSuffixPalindrome ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE length = 0 NEW_LINE for i in range ( n // 2 ) : NEW_LINE INDENT if ( st [ i ] != st [ n - i - 1 ] ) : NEW_LINE INDENT length = i NEW_LINE break NEW_LINE DEDENT DEDENT prefix = " " NEW_LINE suffix = " " NEW_LINE midPal = " " NEW_LINE prefix = st [ : length ] NEW_LINE suffix = st [ n - length : ] NEW_LINE st = st [ length : n - 2 * length + length ] NEW_LINE for i in range ( 1 , len ( st ) + 1 ) : NEW_LINE INDENT y = st [ 0 : i ] NEW_LINE if ( isPalindrome ( y ) ) : NEW_LINE INDENT if ( len ( midPal ) < len ( y ) ) : NEW_LINE INDENT midPal = y NEW_LINE DEDENT DEDENT DEDENT for i in range ( 1 , len ( st ) + 1 ) : NEW_LINE INDENT y = st [ len ( st ) - i ] NEW_LINE if ( isPalindrome ( y ) ) : NEW_LINE INDENT if ( len ( midPal ) < len ( y ) ) : NEW_LINE INDENT midPal = y NEW_LINE DEDENT DEDENT DEDENT answer = prefix + midPal + suffix NEW_LINE return answer NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " abcdfdcecba " ; NEW_LINE print ( PrefixSuffixPalindrome ( st ) ) NEW_LINE DEDENT