generated from threeal/project-starter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsolution.cpp
38 lines (31 loc) · 777 Bytes
/
solution.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
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
class Solution {
public:
std::string removeDuplicateLetters(std::string s) {
std::unordered_map<char, std::size_t> counts;
for (const auto c : s) {
++counts[c];
}
std::unordered_set<char> existed;
std::stack<char> orders;
for (const auto c : s) {
--counts[c];
if (existed.find(c) != existed.end()) continue;
while (!orders.empty() && orders.top() > c && counts[orders.top()] > 0) {
existed.erase(orders.top());
orders.pop();
}
orders.push(c);
existed.insert(c);
}
std::string res;
while (!orders.empty()) {
res = orders.top() + res;
orders.pop();
}
return res;
}
};