Easy to understand O(n) time, O(1) space, 13ms solution


  • 0
    H
    string frequencySort(string s) {
            
            if (s.size() == 0) return "";
            
            int hmap[256] = {0};
            string ret = "";
            
            for (int i = 0; i < s.size(); i++) {
                hmap[s[i] - '\0']++;
            }
            
            for(int i = 0; i < s.size(); i++) {
                int max = 0;
                char index = '\0';
                
                for(int j = 0; j < 256; j++) {
                    if (hmap[j] > max) {
                        max = hmap[j];
                        index = j;
                    }
                }
                
                if (max == 0) break;
                
                while(max) {
                    ret += index;
                    max--;
                }
                hmap[index] = 0;
                
            }
            
            return ret;
            
        }
    

Log in to reply
 

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