Skip to content

1209. Remove All Adjacent Duplicates in String II 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  string removeDuplicates(const string& s, int k) {
    string ans;
    vector<pair<char, int>> stack;

    for (const char c : s)
      if (stack.empty() || stack.back().first != c)
        stack.emplace_back(c, 1);
      else if (++stack.back().second == k)  // stack[-1] == c
        stack.pop_back();

    for (const auto& [c, count] : stack)
      ans.append(count, c);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Item {
  public char c;
  public int freq;
  public Item(char c, int freq) {
    this.c = c;
    this.freq = freq;
  }
}

class Solution {
  public String removeDuplicates(String s, int k) {
    StringBuilder sb = new StringBuilder();
    LinkedList<Item> stack = new LinkedList<>();

    for (final char c : s.toCharArray()) {
      if (!stack.isEmpty() && stack.peek().c == c)
        ++stack.peek().freq;
      else
        stack.push(new Item(c, 1));
      if (stack.peek().freq == k)
        stack.pop();
    }

    while (!stack.isEmpty()) {
      Item item = stack.pop();
      for (int i = 0; i < item.freq; ++i)
        sb.append(item.c);
    }

    return sb.reverse().toString();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def removeDuplicates(self, s: str, k: int) -> str:
    stack = []

    for c in s:
      if not stack or stack[-1][0] != c:
        stack.append([c, 1])
      else:  # stack[-1][0] == c
        stack[-1][1] += 1
        if stack[-1][1] == k:
          stack.pop()

    return ''.join(c * count for c, count in stack)