Remove Duplicate Letters

Desicription

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

Example 1:

1
2
Input: "bcabc"
Output: "abc"

Example 2:

1
2
Input: "cbacdcbc"
Output: "acdb"

Solution

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
class Solution {
public:
std::string removeDuplicateLetters(std::string s) {
auto visit = std::map<char, bool>();
auto count = std::map<char, int>();

for(auto c : s) {
count[c]++;
}

auto res = std::string();
for(auto c : s) {
count[c]--;

if(visit[c]) {
continue;
}

while(!res.empty() && c < res.back() && count[res.back()] != 0) {
visit[res.back()] = false;
res.pop_back();
}

res += c;
visit[c] = true;
}

return res;
}
};