Maximum length palindromic substring such that it starts and ends with given char | Function that returns true if str [ i ... j ] is a palindrome ; Function to return the length of the longest palindromic sub - string such that it starts and ends with the character ch ; If current character is a valid starting index ; Instead of finding the ending index from the beginning , find the index from the end This is because if the current sub - string is a palindrome then there is no need to check the sub - strings of smaller length and we can skip to the next iteration of the outer loop ; If current character is a valid ending index ; If str [ i ... j ] is a palindrome then update the length of the maximum palindrome so far ; Driver code
def isPalindrome ( str , i , j ) : NEW_LINE INDENT while ( i < j ) : NEW_LINE INDENT if ( str [ i ] != str [ j ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT i += 1 ; NEW_LINE j -= 1 ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def maxLenPalindrome ( str , n , ch ) : NEW_LINE INDENT maxLen = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == ch ) : NEW_LINE INDENT for j in range ( n - 1 , i + 1 , - 1 ) : NEW_LINE INDENT if ( str [ j ] == ch ) : NEW_LINE INDENT if ( isPalindrome ( str , i , j ) ) : NEW_LINE INDENT maxLen = max ( maxLen , j - i + 1 ) ; NEW_LINE break ; NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT return maxLen ; NEW_LINE DEDENT str = " lapqooqpqpl " ; NEW_LINE n = len ( str ) ; NEW_LINE ch = ' p ' ; NEW_LINE print ( maxLenPalindrome ( str , n , ch ) ) ; NEW_LINE