-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack5206.java
More file actions
50 lines (47 loc) · 1.44 KB
/
Stack5206.java
File metadata and controls
50 lines (47 loc) · 1.44 KB
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
package stack;
import java.util.Stack;
public class Stack5206 {
public static void main(String[] args) {
System.out.println(removeDuplicates("deeedbbcccbdaa", 3));
}
public static String removeDuplicates(String s, int k) {
if (k > s.length()) {
return s;
}
char[] chars = s.toCharArray();
Stack<Character> input = new Stack<>();
for (int i = 0; i < chars.length; i++) {
input.push(chars[i]);
}
Stack<Character> result = new Stack<>();
char temp = input.pop();
int sameNum = 1;
while (!input.isEmpty()) {
if (input.peek() == temp) {
input.pop();
sameNum++;
} else {
for (int i = 0; i < sameNum; i++) {
result.push(temp);
}
temp = input.pop();
sameNum = 1;
}
if (sameNum == k) {
for (int i = 0; !result.isEmpty() && i < k-1; i++) {
input.push(result.pop());
}
temp = input.pop();
sameNum = 1;
}
}
for (int i = 0; i < sameNum; i++) {
result.push(temp);
}
StringBuilder stringBuilder = new StringBuilder();
while (!result.isEmpty()) {
stringBuilder.append(result.pop());
}
return stringBuilder.toString();
}
}