clueless coding // TODO: be smarter

LeetCode Sort Characters By Frequency: CPP Solution



TL;DR Code Solution


string frequencySort(string s) {

    unordered_map<char, int> map;
    for (int i = 0; i < s.length(); i++) {
        if (map.find(s[i]) == map.end())
            map[s[i]] = 1;
        else
            map[s[i]]++;
    }

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

    return s;
}