Skip to content

Commit 5ca4ef5

Browse files
authored
Create smallest-subsequence-of-distinct-characters.cpp
1 parent bf4ea48 commit 5ca4ef5

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
string smallestSubsequence(string text) {
7+
const int k = 26;
8+
vector<int> count(k);
9+
for (const auto& c : text) {
10+
++count[c - 'a'];
11+
}
12+
13+
vector<bool> lookup(k);
14+
string stk;
15+
for (const auto& c : text) {
16+
if (!lookup[c - 'a']) {
17+
while (!stk.empty() && stk.back() > c &&
18+
count[stk.back() - 'a']) {
19+
lookup[stk.back() - 'a'] = false;
20+
stk.pop_back();
21+
}
22+
stk.push_back(c);
23+
lookup[c - 'a'] = true;
24+
}
25+
--count[c - 'a'];
26+
}
27+
return stk;
28+
}
29+
};

0 commit comments

Comments
 (0)