C++ O(N)


  • 0
    class Solution {
    public:
        string frequencySort(string s) {
            int N = s.size();
            vector<string> sortMap(N+1,"");
            unordered_map<char,int> hash;
            for(char c:s) {
                hash[c]++;
            }
            for(auto h : hash) {
                int cnt = h.second;
                if(cnt>0) {
                    sortMap[cnt].append(h.second,h.first);
                }
            }
            string ans = "";
            for(int i=N;i>=1;i--) {
                if(sortMap[i]=="") continue;
                ans += sortMap[i];
            }
            
    
            return ans;
        }
    };
    

Log in to reply
 

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