C++ simple


  • 0
    class Solution {
    public:
        string removeDuplicateLetters(string s) {
            int hash[256]={0};
            int visited[256]={0};
            for(char c:s) hash[c]++;
            stack<char> stk;
            for(int i=0;i<s.size();i++) {
                if(visited[s[i]]==1) {
                    hash[s[i]] --;
                    continue;
                }
                while(!stk.empty() && s[i]<stk.top() && hash[stk.top()]>0) {
                    visited[stk.top()] = 0;
                    stk.pop();
                }
                stk.push(s[i]);
                visited[s[i]] = 1;
                hash[s[i]] --;
            }
            string ans="";
            while(!stk.empty()) {
                ans = stk.top() + ans;
                stk.pop();
            }
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.