Wednesday, October 4, 2017

451. Sort Characters By Frequency

https://leetcode.com/problems/sort-characters-by-frequency/description/
Solution 1, sort
    string frequencySort(string s) {
        int count['z'+1] = {0};
        for(char c : s) count[c]++;
        sort(s.begin(), s.end(), [&](char& a, char& b)
                   {return count[a]>count[b] || (count[a] == count[b] && a>b);});
        return s;
    }

Solution 2, without a sort
    string frequencySort(string s) {
        unordered_map<char,int> count;
        for(char c: s) count[c]++;
        map<int, string> f2s;
        for(auto &m : count) {
            char c = m.first;
            int n = m.second;
            f2s[n] += string(n, c);
        }
        string res;
        for(map<int,string>::reverse_iterator it=f2s.rbegin(); it!=f2s.rend(); it++)
            res += it->second;
        return res;
    }


No comments:

Post a Comment