leetcode 316 - Remove Duplicate Letters

https://leetcode.com/problems/remove-duplicate-letters/

Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/

Example 1:

Input: s = “bcabc”
Output: “abc”
Example 2:

Input: s = “cbacdcbc”
Output: “acdb”

Constraints:

1 <= s.length <= 104
s consists of lowercase English letters.

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
class Solution {
public:
string removeDuplicateLetters(string s) {
vector<int> count(256, 0);
vector<bool> used(256, false);

for (int c : s)
count[c]++;

stack<char> stk;

for (char c : s) {
if (used[c]) {
count[c]--;
continue;
}

while (!stk.empty()) {
char tmp = stk.top();
if (tmp > c && count[tmp] > 0) {
stk.pop();
used[tmp] = false;
} else {
break;
}
}

stk.push(c);
count[c]--;
used[c] = true;
}

string result;
while (!stk.empty()) {
result.push_back(stk.top());
stk.pop();
}

reverse(result.begin(), result.end());

return result;
}
};