-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprblm316.java
More file actions
40 lines (33 loc) · 1.12 KB
/
prblm316.java
File metadata and controls
40 lines (33 loc) · 1.12 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
import java.util.*;
public class prblm316 {
public static void main(String[] args) {
String s = "bcabc";
System.out.println(removeDuplicateLetters(s));
}
public static String removeDuplicateLetters(String s) {
Map<Character, Integer> lastIndex = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char curr = s.charAt(i);
lastIndex.put(curr, i);
}
Stack<Character> stack = new Stack<>();
Set<Character> seen = new HashSet<>();
for (int i = 0; i < s.length(); i++) {
char curr = s.charAt(i);
if (seen.contains(curr))
continue;
while (!stack.isEmpty() && stack.peek() > curr && lastIndex.get(stack.peek()) > i) {
seen.remove(stack.pop());
}
if (!seen.contains(curr)) {
stack.push(curr);
seen.add(curr);
}
}
StringBuilder str = new StringBuilder();
while (!stack.isEmpty()) {
str.append(stack.pop());
}
return str.reverse().toString();
}
}