Remove All Adjacent Duplicates in String II — Stack with Counts
Advertisement
Problem 267 · Remove All Adjacent Duplicates in String II
Difficulty: Medium · Pattern: Stack with (char, count)
Remove k adjacent identical characters, repeat until no more.
Solutions
# Python
def removeDuplicates(s, k):
stack = [] # (char, count)
for c in s:
if stack and stack[-1][0] == c:
stack[-1] = (c, stack[-1][1]+1)
if stack[-1][1] == k: stack.pop()
else:
stack.append((c, 1))
return ''.join(c*cnt for c, cnt in stack)
// Java
public String removeDuplicates(String s, int k) {
Deque<int[]> stack = new ArrayDeque<>(); // [char, count]
for (char c : s.toCharArray()) {
if (!stack.isEmpty() && stack.peek()[0]==c) {
stack.peek()[1]++;
if (stack.peek()[1]==k) stack.pop();
} else stack.push(new int[]{c, 1});
}
StringBuilder sb = new StringBuilder();
for (int[] pair : stack) for (int i=0;i<pair[1];i++) sb.append((char)pair[0]);
return sb.reverse().toString();
}
Complexity
- Time: O(n)
- Space: O(n)
Advertisement