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 2d52013 commit f016ae5
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions C++/remove-duplicate-letters.cpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,36 @@
// Time: O(n)
// Space: O(k), k is size of the alphabet

// array solution (4ms)
class Solution {
public:
string removeDuplicateLetters(string s) {
array<int, 26> cnts{0};
for (const auto& c : s) {
++cnts[c - 'a'];
}

array<bool, 26> visited{false};
string stk;
for (const auto& c : s) {
if (!visited[c - 'a'] && (stk.empty() || stk.back() != c)) {
while (!stk.empty() && stk.back() >= c && cnts[stk.back() - 'a'] > 0) {
visited[stk.back() - 'a'] = false;
stk.pop_back();
}
stk.push_back(c);
visited[c - 'a'] = true;
}
--cnts[c - 'a'];
}
return stk;
}
};

// Time: O(n)
// Space: O(k), k is size of the alphabet
// hash solution (16ms)
class Solution2 {
public:
string removeDuplicateLetters(string s) {
unordered_map<char, int> cnts;
Expand Down

0 comments on commit f016ae5

Please sign in to comment.