Maximum length palindromic substring for every index such that it starts and ends at that index | Java program for the above approach ; Function to find for every index , longest palindromic substrings starting or ending at that index ; Stores the maximum palindromic substring length for each index ; Traverse the string ; Stores the maximum length of palindromic substring ; Consider that palindromic substring ends at index i ; If current character is a valid starting index ; If S [ i , j ] is palindrome , ; Update the length of the longest palindrome ; Consider that palindromic substring starts at index i ; If current character is a valid ending index ; If str [ i , j ] is palindrome ; Update the length of the longest palindrome ; Update length of the longest palindromic substring for index i ; Print the length of the longest palindromic substring ; Function to return true if S [ i ... j ] is a palindrome ; Iterate until i < j ; If unequal character encountered ; Otherwise ; Driver Code
class GFG { public static void printLongestPalindrome ( String S , int N ) { int palLength [ ] = new int [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { int maxlength = 1 ; for ( int j = 0 ; j < i ; j ++ ) { if ( S . charAt ( j ) == S . charAt ( i ) ) { if ( isPalindrome ( S , j , i ) ) { maxlength = i - j + 1 ; break ; } } } for ( int j = N - 1 ; j > i ; j -- ) { if ( S . charAt ( j ) == S . charAt ( i ) ) { if ( isPalindrome ( S , i , j ) ) { maxlength = Math . max ( j - i + 1 , maxlength ) ; break ; } } } palLength [ i ] = maxlength ; } for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( palLength [ i ] + " ▁ " ) ; } } public static boolean isPalindrome ( String S , int i , int j ) { while ( i < j ) { if ( S . charAt ( i ) != S . charAt ( j ) ) return false ; i ++ ; j -- ; } return true ; } public static void main ( String [ ] args ) { String S = " bababa " ; int N = S . length ( ) ; printLongestPalindrome ( S , N ) ; } }