Print the longest palindromic prefix of a given string | Java program for the above approach ; Function to find the longest prefix which is palindromic ; Find the length of the given String ; For storing the length of longest prefix palindrome ; Loop to check the subString of all length from 1 to N which is palindrome ; String of length i ; To store the reversed of temp ; Reversing String temp2 ; If String temp is palindromic then update the length ; Print the palindromic String of max_len ; Driver Code ; Given String ; Function Call
import java . util . * ; class GFG { static void LongestPalindromicPrefix ( String s ) { int n = s . length ( ) ; int max_len = 0 ; for ( int len = 1 ; len <= n ; len ++ ) { String temp = s . substring ( 0 , len ) ; String temp2 = temp ; temp2 = reverse ( temp2 ) ; if ( temp . equals ( temp2 ) ) { max_len = len ; } } System . out . print ( s . substring ( 0 , max_len ) ) ; } 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 = " abaab " ; LongestPalindromicPrefix ( str ) ; } }