-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy path1209. Remove All Adjacent Duplicates in String II
79 lines (63 loc) · 1.91 KB
/
1209. Remove All Adjacent Duplicates in String II
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
74
75
76
77
78
79
class Solution {
public String removeDuplicates(String s, int k) {
Stack<Character> main = new Stack<>();
for(char c: s.toCharArray()){
Stack<Character> temp = new Stack<>();
temp.push(c);
while(!main.isEmpty() && main.peek()==c){
temp.push(main.pop());
}
if(temp.size()!=k){
while(!temp.isEmpty()){
main.push(temp.pop());
}
}
}
StringBuilder sb= new StringBuilder();
while(!main.isEmpty()){
sb.append(main.pop());
}
return sb.reverse().toString();
}
}
class Solution {
public String removeDuplicates(String s, int k) {
Stack<int[]> main = new Stack<>();
for(char c: s.toCharArray()){
if(!main.isEmpty() && main.peek()[0] == c){
main.peek()[1]++;
}
else{
main.push(new int[]{c,1});
}
if(main.peek()[1]==k){
main.pop();
}
}
StringBuilder sb= new StringBuilder();
while(!main.isEmpty()){
int[] top = main.pop();
while(top[1]-->0)
sb.append((char) top[0]);
}
return sb.reverse().toString();
}
}
class Solution {
public String removeDuplicates(String s, int k) {
int count = 1;
for(int i=1;i<s.length();i++){
if(s.charAt(i)==s.charAt(i-1)){
count++;
}
else{
count=1;
}
if(count==k){
String reduced = s.substring(0,i-k+1) + s.substring(i+1);
return removeDuplicates(reduced,k);
}
}
return s;
}
}