欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

排序LeetCode 451 Sort Characters By Frequency

程序员文章站 2022-05-26 22:25:57
...

LeetCode 451

Sort Characters By Frequency

class Solution {
public:
    static bool cmp(pair<char, int>& p, pair<char, int>& q) {
        return p.second>q.second;
    }
    string frequencySort(string s) {
        if (s.length()==0||s.length()==1||s.length()==2) return s;
        string str = "";
        map<char, int> character;
        for (int i = 0; i < s.length(); i++)  {
            character[s[i]]++;
        }
        vector<pair<char, int>> v(character.begin(), character.end());
        sort(v.begin(), v.end(), cmp);
        for (int i = 0; i < v.size(); i++) {
            while(v[i].second--) {
                str += v[i].first;
            }
        }
        return str;
    }
};
相关标签: sort