Skip to content

Commit 6f5cda1

Browse files
committed
Sixty-Nine Commit: Add Remove All Adjacent Duplicates In String II problem to Monotonic Stack section
1 parent a01150d commit 6f5cda1

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package Monotonic_Stack;
2+
3+
// Problem Statement: Remove All Adjacent Duplicates in String II (medium)
4+
// LeetCode Question: 1209. Remove All Adjacent Duplicates in String II
5+
6+
import java.util.Stack;
7+
8+
public class Problem_5_Remove_All_Adjacent_Duplicates_In_String11 {
9+
public String removeDuplicates(String s, int k) {
10+
Stack<int[]> stack = new Stack<>();
11+
for (char c : s.toCharArray()) {
12+
if (!stack.isEmpty() && stack.peek()[0] == c) {
13+
stack.peek()[1]++;
14+
} else {
15+
stack.push(new int[]{c, 1});
16+
}
17+
if (stack.peek()[1] == k) {
18+
stack.pop();
19+
}
20+
}
21+
StringBuilder result = new StringBuilder();
22+
while (!stack.isEmpty()) {
23+
int[] top = stack.pop();
24+
result.append(String.valueOf((char) top[0]).repeat(top[1]));
25+
}
26+
return result.reverse().toString();
27+
}
28+
}

0 commit comments

Comments
 (0)