-
Notifications
You must be signed in to change notification settings - Fork 1
/
Solution02.java
39 lines (28 loc) · 954 Bytes
/
Solution02.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
import java.util.*;
class Solution02 {
public String removeDuplicateLetters(String s) {
Set<Character> hashSet = new HashSet<>();
Map<Character, Integer> counter = new HashMap<>();
Deque<Character> stack = new LinkedList<>();
for (char c : s.toCharArray()) {
counter.putIfAbsent(c, 0);
counter.computeIfPresent(c, (key, value) -> value + 1);
}
for (char c : s.toCharArray()) {
counter.put(c, counter.get(c) - 1);
if(hashSet.contains(c)) {
continue;
}
while (!stack.isEmpty() && c < stack.peek() && counter.get(stack.peek()) > 0) {
hashSet.remove(stack.pop());
}
stack.push(c);
hashSet.add(c);
}
String result = "";
while (!stack.isEmpty()) {
result = stack.pop() + result;
}
return result;
}
}