Skip to content

Commit 3e71da9

Browse files
committed
34ms, 41%, 92%.
1 parent 1d0be4e commit 3e71da9

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
* @lc app=leetcode id=1209 lang=java
3+
*
4+
* [1209] Remove All Adjacent Duplicates in String II
5+
*/
6+
7+
// @lc code=start
8+
9+
class Solution {
10+
public String removeDuplicates(String s, int k) {
11+
StringBuilder sb = new StringBuilder(s);
12+
Stack<Integer> counts = new Stack<>();
13+
// walk through the string
14+
for (int i = 0; i < sb.length(); ++i) {
15+
if (i == 0 || sb.charAt(i) != sb.charAt(i - 1)) {
16+
counts.push(1);
17+
} else {
18+
// If the current character is the same as the one before,
19+
// increment the count on the top of the stack.
20+
int incremented = counts.pop() + 1;
21+
// If the count on the top of the stack equals k,
22+
// erase last k characters and pop from the stack.
23+
if (incremented == k) {
24+
sb.delete(i - k + 1, i + 1);
25+
i = i - k;
26+
} else {
27+
counts.push(incremented);
28+
}
29+
}
30+
}
31+
return sb.toString();
32+
}
33+
}
34+
// @lc code=end

0 commit comments

Comments
 (0)