Leetcode 1320 Solution

This article provides solution to leetcode question 1320 (remove-all-adjacent-duplicates-in-string-ii)

https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii

Solution

class Solution:
    def removeDuplicates(self, s: str, k: int) -> str:
        stack = [('0', 1)]

        for ch in s:
            last_ch, last_cnt = stack[-1]

            cnt = 0
            if ch == last_ch:
                cnt = last_cnt + 1
            else:
                cnt = 1

            if cnt == k:
                for i in range(k - 1):
                    stack.pop()
            else:
                stack.append((ch, cnt))

        return "".join([ch for ch, _ in stack])[1:]