Remove all duplicate adjacent characters from a string using Stack | Function to remove adjacent duplicate elements ; Store the string without duplicate elements ; Store the index of str ; Traverse the string str ; Checks if stack is empty or top of the stack is not equal to current character ; If top element of the stack is equal to the current character ; If stack is empty ; If stack is not Empty ; Driver Code
def ShortenString ( str1 ) : NEW_LINE INDENT st = [ ] NEW_LINE i = 0 NEW_LINE while i < len ( str1 ) : NEW_LINE INDENT if len ( st ) == 0 or str1 [ i ] != st [ - 1 ] : NEW_LINE INDENT st . append ( str1 [ i ] ) NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT st . pop ( ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT if len ( st ) == 0 : NEW_LINE INDENT return ( " Empty ▁ String " ) NEW_LINE DEDENT else : NEW_LINE INDENT short_string = " " NEW_LINE for i in st : NEW_LINE INDENT short_string += str ( i ) NEW_LINE DEDENT return ( short_string ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " azzxzy " NEW_LINE print ( ShortenString ( str1 ) ) NEW_LINE DEDENT