Skip to content

Commit

Permalink
Update remove-duplicate-letters.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 committed Dec 9, 2015
1 parent bd423f4 commit e787f3a
Showing 1 changed file with 8 additions and 8 deletions.
16 changes: 8 additions & 8 deletions C++/remove-duplicate-letters.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,23 @@ class Solution {
public:
string removeDuplicateLetters(string s) {
const int k = 26;
vector<int> cnts(k);
vector<int> remaining(k);
for (const auto& c : s) {
++cnts[c - 'a'];
++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 && cnts[stk.back() - '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;
}
--cnts[c - 'a'];
--remaining[c - 'a'];
}
return stk;
}
Expand All @@ -34,23 +34,23 @@ class Solution {
class Solution2 {
public:
string removeDuplicateLetters(string s) {
unordered_map<char, int> cnts;
unordered_map<char, int> remaining;
for (const auto& c : s) {
++cnts[c];
++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 && cnts[stk.back()]) {
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);
}
--cnts[c];
--remaining[c];
}
return stk;
}
Expand Down

0 comments on commit e787f3a

Please sign in to comment.