Skip to content

Commit 42ecac7

Browse files
Create: 1209-remove-all-adjacent-duplicates-in-string-ii.java
Signed-off-by: Aliaksei <[email protected]>
1 parent 489140e commit 42ecac7

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public String removeDuplicates(String s, int k) {
3+
Stack<Pair<Character, Integer>> stack = new Stack<>();
4+
char[] ss = s.toCharArray();
5+
6+
for (char current : ss) {
7+
if (!stack.isEmpty() && stack.peek().getKey() == current) {
8+
int topCharCount = stack.pop().getValue();
9+
stack.push(new Pair<>(current, topCharCount + 1));
10+
} else {
11+
stack.push(new Pair<>(current, 1));
12+
}
13+
14+
if (stack.peek().getValue() == k) {
15+
stack.pop();
16+
}
17+
}
18+
19+
StringBuilder result = new StringBuilder();
20+
21+
while (!stack.isEmpty()) {
22+
Pair<Character, Integer> poppedPair = stack.pop();
23+
for (int i = 0; i < poppedPair.getValue(); i++) {
24+
result.append(poppedPair.getKey());
25+
}
26+
}
27+
28+
return result.reverse().toString();
29+
}
30+
}

0 commit comments

Comments
 (0)