My simple c++ solution using vector


  • 0
    K
    class Solution {
    public:
    string removeDuplicateLetters(string s) {
        vector<char>v;
        unordered_map<char, int>map;
        string res="";
        int size=s.size();
        if(size<=1)return s;
        for(int i=0;i<size;i++)
        {
            if(map.find(s[i])==map.end())map[s[i]]=1;
            else map[s[i]]++;
        }
        v.push_back(s[0]);
        for(int i=1;i<size;i++)
        {
            
            if(find(v.begin(), v.end(), s[i])==v.end()){
                while(!v.empty() && v.back() > s[i] && map[v.back()]>1)
                {
                    map[v.back()]--;
                    v.pop_back();
                    
                }
                v.push_back(s[i]);
            }
           else map[s[i]]--;
        }
        for(int i=0;i<v.size();i++)res+=v[i];
        
        return res;
    }
    

    };


Log in to reply
 

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