-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSmallestSubsequenceDistinctCharacters.java
54 lines (36 loc) · 1.42 KB
/
SmallestSubsequenceDistinctCharacters.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
private static int ALPH_SIZE = 26;
//Time: O(n) where n is string size
//Space: O(1)
public String removeDuplicateLetters(String s) {
int[] lastIndexes = buildLastIndexArray(s);
Stack<Character> stack = new Stack();
Set<Character> alreadyUsed = new HashSet<>();
char[] charArray = s.toCharArray();
for(int i = 0; i < charArray.length; i++) {
char c = charArray[i];
if (alreadyUsed.contains(c)) continue;
while(!stack.isEmpty() && c < stack.peek() && lastIndexes[stack.peek() - 'a'] > i) {
char removed = stack.pop();
alreadyUsed.remove(removed);
}
stack.push(c);
alreadyUsed.add(c);
}
return stackToString(stack);
}
private int[] buildLastIndexArray(String s) {
int[] indexes = new int[ALPH_SIZE];
for(int i = 0; i < s.length(); i++) {
indexes[s.charAt(i) - 'a'] = i;
}
return indexes;
}
private String stackToString(Stack<Character> stack) {
StringBuilder builder = new StringBuilder();
while(!stack.isEmpty()) {
builder.append(stack.pop());
}
return builder.reverse().toString();
}
}