1209. 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 = []
        for char in s:
            if stack and stack[-1][0] == char:
                stack[-1][1] += 1
                if stack [-1][1] == k:
                    stack.pop()
            # 注意这里有else
            else:
                # 注意上面有修改 stack[-1][1]的值,因此只能选list,不能tuple
                stack.append([char, 1])
        return "".join(c*count for c, count in stack)

时间复杂度:O(n) 空间复杂度:O(n)

Last updated