1047. Remove All Adjacent Duplicates In String - cocoder39/coco39_LC GitHub Wiki

1047. Remove All Adjacent Duplicates In String

class Solution:
    def removeDuplicates(self, s: str) -> str:
        stack = []
        for ch in s:
            if not stack or ch != stack[-1]:
                stack.append(ch)
            else:
                stack.pop()

        return ''.join(stack)  

follow up: remove all adjacent duplicates instead of just pairs: "cabbbaaca" -> "a"

class Solution:
    def removeDuplicates(self, s: str) -> str:
        stack = []
        i = 0
        while i < len(s):
            if stack and s[i] == stack[-1]:
                while i < len(s) and s[i] == stack[-1]:
                    i += 1
                stack.pop()
            else:
                stack.append(s[i])
                i += 1

        return ''.join(stack)