1class Solution {2public:3string removeDuplicateLetters(string s) {4int len = s.size();5string res = "";6unordered_map<char, int> M;7unordered_map<char, bool> V;8stack<int> S;910for (auto c : s) {11if (M.find(c) == M.end())12M[c] = 1;13else14M[c]++;15}16for (unordered_map<char, int>::iterator iter = M.begin(); iter != M.end(); iter++)17V[iter->first] = false;1819cout << M.size() << V.size() << endl;20for (int i = 0; i < len; i++) {21M[s[i]]--;22if (V[s[i]] == true) continue;2324while (!S.empty() and s[i] < s[S.top()] and M[s[S.top()]] > 0) {25V[s[S.top()]] = false;26S.pop();27}28S.push(i);29V[s[i]] = true;30}31while (!S.empty()) {32res = s[S.top()] + res;33S.pop();34}35return res;36}37};3839Analysis Time complexity O(n)40space complexity O(n)