c++ 16ms Solution by using vector and priority_queue


  • 0
    public:
        string frequencySort(string s) {
            vector<int> hash(128);
            for(int i=0;i<s.size();++i){
                ++hash[s[i]];
            }
            auto compare = [](pair<int,int> &a,pair<int,int> &b){
                return a.second<b.second;
            };
            priority_queue <pair<int,int>,vector<pair<int,int>>,decltype(compare) > pq(compare);
            for(int i=0;i<128;++i){
                if(hash[i])
                    pq.emplace(i,hash[i]);
            }
            ostringstream os;
            while(!pq.empty()){
                pair<int,int> temp = pq.top();
                pq.pop();
                while(temp.second--){
                    os<<(char)temp.first;
                }
            }
            return os.str();
        }
    };
    
    

Log in to reply
 

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