-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRemoveDuplicates.java
More file actions
55 lines (44 loc) · 1.26 KB
/
Copy pathRemoveDuplicates.java
File metadata and controls
55 lines (44 loc) · 1.26 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
51
52
53
54
55
class Node {
private char key;
private int value;
public Node(char key, int value) {
this.key = key;
this.value = value;
}
public char getKey() {
return key;
}
public int getValue() {
return value;
}
}
class Solution {
public String removeDuplicates(String s, int k) {
if (s.isEmpty() || s.length() < k){
return s;
}
Deque<Node> stack = new ArrayDeque<>();
for (char c : s.toCharArray()){
if (stack.isEmpty()) {
stack.push(new Node(c, 1));
} else {
if (stack.peek().getKey() == c){
Node temp = stack.pop();
stack.push(new Node(c, temp.getValue() + 1));
} else {
stack.push(new Node(c, 1));
}
}
if (stack.peek().getValue() == k) {
stack.pop();
}
}
StringBuilder sb = new StringBuilder();
for (Node node : stack){
for (int i = 0; i < node.getValue(); i++){
sb.append(node.getKey());
}
}
return sb.reverse().toString();
}
}