-
Notifications
You must be signed in to change notification settings - Fork 27
/
#Day10-Kaushik.java
37 lines (30 loc) · 986 Bytes
/
#Day10-Kaushik.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
class Day10 {
public String removeDuplicateLetters(String s) {
int[] last = new int[26];
boolean[] seen = new boolean[26];
// Last occurrance
int index = 0;
for(char current : s.toCharArray()) {
last[current - 'a'] = index;
index++;
}
ArrayDeque<Integer> stack = new ArrayDeque<>();
StringBuilder sb = new StringBuilder();
int currIndex;
index = -1;
for(char current : s.toCharArray()) {
currIndex = current - 'a';
index++;
if(seen[currIndex]) { continue; }
while(!stack.isEmpty() && currIndex < stack.peek() && last[stack.peek()] > index) {
seen[stack.pop()] = false;
}
stack.push(currIndex);
seen[currIndex] = true;
}
while(!stack.isEmpty()) {
sb.insert(0,(char)(stack.pop() + 'a'));
}
return sb.toString();
}
}