Posted on

Description

Submission

class Solution {
public:
    string frequencySort(string s) {
        unordered_map<char, int> freq;
        unordered_set<char> alphabet;
        for(char ch: s) {
            ++freq[ch];
            alphabet.insert(ch);
        }

        vector<int> uniq(alphabet.begin(), alphabet.end());

        sort(uniq.begin(), uniq.end(), [&freq](char a, char b) {
            return freq[a] > freq[b];
        });

        unordered_map<char, int> order;
        for(int i = 0; i < uniq.size(); ++i) {
            order[uniq[i]] = i;
        }

        sort(s.begin(), s.end(), [&order](char a, char b) {
            return order[a] < order[b];
        });

        return s;
    }
};
class Solution {
public:
    string frequencySort(string s) {
        unordered_map<char, int> freq;
        for(char ch: s) {
            ++freq[ch];
        }

        sort(s.begin(), s.end(), [&freq](char a, char b) {
            if(freq[a] == freq[b]) return a > b;
            return freq[a] > freq[b];
        });

        return s;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *