thiagowfx's avatar

Β¬ just serendipity πŸ€ (not just serendipity)

LeetCode #1047: Remove All Adjacent Duplicates In String

β€’ 79 words β€’ 1 min

LeetCode #1047: Remove All Adjacent Duplicates In String:

Initial:

python
class Solution:
    def removeDuplicates(self, s: str) -> str:
        stack = []
        ans = []

        for c in s:
            if not stack:
                stack.append(c)
                ans.append(c)
            else:
                if stack[-1] != c:
                    stack.append(c)
                    ans.append(c)
                else:
                    stack.pop()
                    ans.pop()

        return ''.join(ans)

Optimized:

python
class Solution:
    def removeDuplicates(self, s: str) -> str:
        stack = []
        ans = []

        for c in s:
            if not stack or stack[-1] != c:
                stack.append(c)
                ans.append(c)
            else:
                stack.pop()
                ans.pop()

        return ''.join(ans)