Longest Palindrome in a String formed by concatenating its prefix and suffix | Java program to find the 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
import java . util . * ; class GFG { static boolean isPalindrome ( String r ) { String p = r ; p = reverse ( p ) ; return ( r . equals ( p ) ) ; } static String PrefixSuffixPalindrome ( String str ) { int n = str . length ( ) , len = 0 ; for ( int i = 0 ; i < n / 2 ; i ++ ) { if ( str . charAt ( i ) != str . charAt ( n - i - 1 ) ) { len = i ; break ; } } String prefix = " " , suffix = " " ; String midPal = " " ; prefix = str . substring ( 0 , len ) ; suffix = str . substring ( n - len ) ; str = str . substring ( len , ( n - 2 * len ) + len ) ; for ( int i = 1 ; i <= str . length ( ) ; i ++ ) { String y = str . substring ( 0 , i ) ; if ( isPalindrome ( y ) ) { if ( midPal . length ( ) < y . length ( ) ) { midPal = y ; } } } for ( int i = 1 ; i <= str . length ( ) ; i ++ ) { String y = str . substring ( str . length ( ) - i ) ; if ( isPalindrome ( y ) ) { if ( midPal . length ( ) < y . length ( ) ) { midPal = y ; } } } String answer = prefix + midPal + suffix ; return answer ; } static String reverse ( String input ) { char [ ] a = input . toCharArray ( ) ; int l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . valueOf ( a ) ; } public static void main ( String [ ] args ) { String str = " abcdfdcecba " ; System . out . print ( PrefixSuffixPalindrome ( str ) ) ; } }