-
Notifications
You must be signed in to change notification settings - Fork 0
/
1209.remove-all-adjacent-duplicates-in-string-ii.java
73 lines (53 loc) · 1.67 KB
/
1209.remove-all-adjacent-duplicates-in-string-ii.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class Solution {
public String removeDuplicates(String s, int k) {
Stack<Pair> stk = new Stack<>();
stk.push(new Pair(s.charAt(0), 1));
int i=1;
while(i<s.length()){
if(i<s.length() && stk.peek().ch == s.charAt(i))
{
// while
stk.peek().c++;
}else{
stk.push(new Pair(s.charAt(i), 1));
}
i++;
}
// System.out.println(stk);
Stack<Pair> stk2 = new Stack<>();
while(!stk.isEmpty()){
Pair curr = stk.pop();
if(!stk2.isEmpty() && stk2.peek().ch == curr.ch){
if((stk2.peek().c + curr.c)%k == 0)
stk2.pop();
else
stk2.peek().c = (stk2.peek().c + curr.c)%k;
}else if(curr.c != k){
curr.c = curr.c%k;
stk2.push(curr);
}
}
// System.out.println(stk2);
StringBuilder res = new StringBuilder();
while(!stk2.isEmpty()){
Pair curr = stk2.pop();
while(curr.c > 0){
curr.c--;
res.append(curr.ch);
}
}
return res.toString();
}
class Pair{
int c;
char ch;
Pair(char ch, int c){
this.c = c;
this.ch = ch;
}
@Override
public String toString(){
return this.ch+" "+this.c;
}
}
}