316. Remove Duplicate Letters
Input: "bcabc"
Output: "abc"Input: "cbacdcbc"
Output: "acdb"// Greedy
string removeDuplicateLetters(string s) { // time: O(n); space: O(1)
vector<int> dict(26, 0);
vector<bool> visited(26, false);
for (char ch : s) ++dict[ch - 'a'];
string res;
for (char ch : s) {
int idx = ch - 'a';
--dict[idx];
if (visited[idx]) continue;
while (ch < res.back() && dict[res.back() - 'a']) {
visited[res.back() - 'a'] = false;
res.pop_back();
}
res += ch;
visited[idx] = true;
}
return res;
}Last updated