forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
remove-duplicate-letters.cpp
57 lines (53 loc) · 1.58 KB
/
remove-duplicate-letters.cpp
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
55
56
57
// Time: O(n)
// Space: O(k), k is size of the alphabet
// vector solution, need to know size of the alphabet in advance (4ms)
class Solution {
public:
string removeDuplicateLetters(string s) {
const int k = 26;
vector<int> remaining(k);
for (const auto& c : s) {
++remaining[c - 'a'];
}
vector<bool> in_stack(k);
string stk;
for (const auto& c : s) {
if (!in_stack[c - 'a']) {
while (!stk.empty() && stk.back() > c && remaining[stk.back() - 'a']) {
in_stack[stk.back() - 'a'] = false;
stk.pop_back();
}
stk.push_back(c);
in_stack[c - 'a'] = true;
}
--remaining[c - 'a'];
}
return stk;
}
};
// Time: O(n)
// Space: O(k), k is size of the alphabet
// hash solution, no need to know size of the alphabet in advance (16ms)
class Solution2 {
public:
string removeDuplicateLetters(string s) {
unordered_map<char, int> remaining;
for (const auto& c : s) {
++remaining[c];
}
unordered_set<char> in_stack;
string stk;
for (const auto& c : s) {
if (!in_stack.count(c)) {
while (!stk.empty() && stk.back() > c && remaining[stk.back()]) {
in_stack.erase(stk.back());
stk.pop_back();
}
stk.push_back(c);
in_stack.emplace(c);
}
--remaining[c];
}
return stk;
}
};