LeetCode451(2021.7.3)

LC451. 根据字符出现频率排序

class Solution {
public:
    bool static cmp(const pair<char,int>& a,const pair<char,int>& b) {
        if (a.second == b.second) return a.first < b.first;
        else return a.second > b.second;
    }

    string frequencySort(string s) {
        map<char, int> res;
        string ans = "";
        for (char i:s) res[i]++;
        vector<pair<char,int>> v(res.begin(),res.end());
        sort(v.begin(), v.end(), cmp);
        for (auto i:v) for (int j = 0; j < i.second; ++j) ans+=i.first;
        return ans;
    }
};

发表评论