-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path1081.Smallest-Subsequence-of-Distinct-Characters.java
46 lines (40 loc) · 1.31 KB
/
1081.Smallest-Subsequence-of-Distinct-Characters.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
// https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/
//
// algorithms
// Medium (38.69%)
// Total Accepted: 1,667
// Total Submissions: 4,311
// beats 100.0% of java submissions
class Solution {
public String smallestSubsequence(String text) {
int len = text.length();
LinkedList<Character> stack = new LinkedList<>();
int[] lastIdx = new int[26];
boolean[] isUsed = new boolean[26];
Arrays.fill(lastIdx, -1);
for (int i = 0; i < len; i++) {
lastIdx[text.charAt(i) - 'a'] = i;
}
for (int i = 0; i < len; i++) {
char ch = text.charAt(i);
while (!isUsed[ch - 'a'] && !stack.isEmpty()) {
char last = stack.peekLast();
if (ch <= last && lastIdx[last - 'a'] >= i) {
stack.pollLast();
isUsed[last - 'a'] = false;
} else {
break;
}
}
if (!isUsed[ch - 'a']) {
stack.offerLast(ch);
isUsed[ch - 'a'] = true;
}
}
StringBuilder sb = new StringBuilder();
for (Character ch : stack) {
sb.append(ch);
}
return sb.toString();
}
}