Maximum length palindromic substring for every index such that it starts and ends at that index | Function to return true if S [ i ... j ] is a palindrome ; Iterate until i < j ; If unequal character encountered ; Otherwise ; 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 ; Driver Code
def isPalindrome ( S , i , j ) : NEW_LINE INDENT while ( i < j ) : NEW_LINE INDENT if ( S [ i ] != S [ j ] ) : NEW_LINE return False NEW_LINE i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def printLongestPalindrome ( S , N ) : NEW_LINE INDENT palLength = [ 0 for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT maxlength = 1 NEW_LINE for j in range ( i ) : NEW_LINE if ( S [ j ] == S [ i ] ) : NEW_LINE INDENT if ( isPalindrome ( S , j , i ) ) : NEW_LINE maxlength = i - j + 1 NEW_LINE break NEW_LINE DEDENT j = N - 1 NEW_LINE while ( j > i ) : NEW_LINE if ( S [ j ] == S [ i ] ) : NEW_LINE INDENT if ( isPalindrome ( S , i , j ) ) : NEW_LINE maxlength = max ( j - i + 1 , maxlength ) NEW_LINE break NEW_LINE DEDENT j -= 1 NEW_LINE palLength [ i ] = maxlength NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( palLength [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " bababa " NEW_LINE N = len ( S ) NEW_LINE printLongestPalindrome ( S , N ) NEW_LINE DEDENT