Skip to content

Commit d9a00db

Browse files
committed
feat(leetcode): add No.1081
1 parent b28b40f commit d9a00db

File tree

4 files changed

+46
-0
lines changed

4 files changed

+46
-0
lines changed
File renamed without changes.
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/
2+
//
3+
// algorithms
4+
// Medium (38.69%)
5+
// Total Accepted: 1,667
6+
// Total Submissions: 4,311
7+
// beats 100.0% of java submissions
8+
9+
class Solution {
10+
public String smallestSubsequence(String text) {
11+
int len = text.length();
12+
LinkedList<Character> stack = new LinkedList<>();
13+
14+
int[] lastIdx = new int[26];
15+
boolean[] isUsed = new boolean[26];
16+
Arrays.fill(lastIdx, -1);
17+
for (int i = 0; i < len; i++) {
18+
lastIdx[text.charAt(i) - 'a'] = i;
19+
}
20+
21+
for (int i = 0; i < len; i++) {
22+
char ch = text.charAt(i);
23+
while (!isUsed[ch - 'a'] && !stack.isEmpty()) {
24+
char last = stack.peekLast();
25+
if (ch <= last && lastIdx[last - 'a'] >= i) {
26+
stack.pollLast();
27+
isUsed[last - 'a'] = false;
28+
} else {
29+
break;
30+
}
31+
}
32+
33+
if (!isUsed[ch - 'a']) {
34+
stack.offerLast(ch);
35+
isUsed[ch - 'a'] = true;
36+
}
37+
}
38+
39+
StringBuilder sb = new StringBuilder();
40+
for (Character ch : stack) {
41+
sb.append(ch);
42+
}
43+
44+
return sb.toString();
45+
}
46+
}

0 commit comments

Comments
 (0)