Skip to content

Commit aef4f93

Browse files
authored
Create 1209. Remove All Adjacent Duplicates in String II
1 parent 31f6995 commit aef4f93

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

Diff for: 1209. Remove All Adjacent Duplicates in String II

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
class Solution {
2+
public String removeDuplicates(String s, int k) {
3+
Stack<Character> main = new Stack<>();
4+
5+
for(char c: s.toCharArray()){
6+
Stack<Character> temp = new Stack<>();
7+
temp.push(c);
8+
9+
while(!main.isEmpty() && main.peek()==c){
10+
temp.push(main.pop());
11+
}
12+
13+
if(temp.size()!=k){
14+
while(!temp.isEmpty()){
15+
main.push(temp.pop());
16+
}
17+
}
18+
}
19+
20+
StringBuilder sb= new StringBuilder();
21+
22+
while(!main.isEmpty()){
23+
sb.append(main.pop());
24+
}
25+
26+
return sb.reverse().toString();
27+
}
28+
}
29+
30+
class Solution {
31+
public String removeDuplicates(String s, int k) {
32+
Stack<int[]> main = new Stack<>();
33+
34+
for(char c: s.toCharArray()){
35+
if(!main.isEmpty() && main.peek()[0] == c){
36+
main.peek()[1]++;
37+
}
38+
else{
39+
main.push(new int[]{c,1});
40+
}
41+
42+
if(main.peek()[1]==k){
43+
main.pop();
44+
}
45+
}
46+
47+
StringBuilder sb= new StringBuilder();
48+
49+
while(!main.isEmpty()){
50+
int[] top = main.pop();
51+
52+
while(top[1]-->0)
53+
sb.append((char) top[0]);
54+
}
55+
56+
return sb.reverse().toString();
57+
}
58+
}
59+
60+
class Solution {
61+
public String removeDuplicates(String s, int k) {
62+
int count = 1;
63+
for(int i=1;i<s.length();i++){
64+
if(s.charAt(i)==s.charAt(i-1)){
65+
count++;
66+
}
67+
else{
68+
count=1;
69+
}
70+
71+
if(count==k){
72+
String reduced = s.substring(0,i-k+1) + s.substring(i+1);
73+
return removeDuplicates(reduced,k);
74+
}
75+
}
76+
77+
return s;
78+
}
79+
}

0 commit comments

Comments
 (0)