Check if the characters in a string form a Palindrome in O ( 1 ) extra space | Utility function to get the position of first character in the string ; Get the position of first character in the string ; Utility function to get the position of last character in the string ; Get the position of last character in the string ; Function to check if the characters in the given string forms a Palindrome in O ( 1 ) extra space ; break , when all letters are checked ; if mismatch found , break the loop ; Driver code
def firstPos ( str , start , end ) : NEW_LINE INDENT firstChar = - 1 NEW_LINE for i in range ( start , end + 1 ) : NEW_LINE INDENT if ( str [ i ] >= ' a ' and str [ i ] <= ' z ' ) : NEW_LINE INDENT firstChar = i NEW_LINE break NEW_LINE DEDENT DEDENT return firstChar NEW_LINE DEDENT def lastPos ( str , start , end ) : NEW_LINE INDENT lastChar = - 1 NEW_LINE for i in range ( start , end - 1 , - 1 ) : NEW_LINE INDENT if ( str [ i ] >= ' a ' and str [ i ] <= ' z ' ) : NEW_LINE INDENT lastChar = i NEW_LINE break NEW_LINE DEDENT DEDENT return lastChar NEW_LINE DEDENT def isPalindrome ( str ) : NEW_LINE INDENT firstChar = 0 NEW_LINE lastChar = len ( str ) - 1 NEW_LINE ch = True NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT firstChar = firstPos ( str , firstChar , lastChar ) ; NEW_LINE lastChar = lastPos ( str , lastChar , firstChar ) ; NEW_LINE if ( lastChar < 0 or firstChar < 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( str [ firstChar ] == str [ lastChar ] ) : NEW_LINE INDENT firstChar += 1 NEW_LINE lastChar -= 1 NEW_LINE continue NEW_LINE DEDENT ch = False NEW_LINE break NEW_LINE DEDENT return ( ch ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " m TABSYMBOL a ▁ 343 ▁ la ▁ y ▁ a ▁ l ▁ am " NEW_LINE if ( isPalindrome ( str ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT