C++ solution using vector


  • 0
    K
    class Solution {
    public:
        string frequencySort(string s) {
            vector<pair<char,int>>cnt(256);
            //O(n)
            for(char c:s)
            {
                cnt[c].first=c;
                cnt[c].second++;
            }
            //O(1)
            sort(cnt.begin(),cnt.end(),[](pair<char,int>&a,pair<char,int>&b){return a.second>b.second;});
            string res="";
            //O(n)
            for(auto p:cnt)
                res+=string(p.second,p.first);
            return res;
        }
    };

Log in to reply
 

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