Easy to understand C++ solution, using vector, map. Who tell me the space and time complexity? Thank you!

  • 0
    class Solution {
        string frequencySort(string s)
            vector<int> counter(256, 0);
            map<int, string> sorter;
            for (auto& c : s)
                counter[c] ++;
            for (int i = 0; i<256; i++)
                if (counter[i])
                    if (sorter.count(counter[i]))
                        sorter[counter[i]] += char(i);
                        sorter[counter[i]] = string(1, char(i));
            string res;
            for (auto it = sorter.rbegin(); it != sorter.rend(); it++)
                for (auto c : it->second)
                    res += string(it->first, c);
            return res;

Log in to reply

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