File tree 1 file changed +34
-0
lines changed
1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments