Sort Characters By Frequency(C++根据字符出现频率排序)

解题思路:

(1)自定义排序

class Solution {
public:
    string frequencySort(string s) {
        map<char,int> mp;
        for(int i=0;i<s.length();i++) {
            mp[s[i]]++;
        }
        
        vector<pair<char,int>> v;
        for(auto it=mp.begin();it!=mp.end();it++) {
            v.push_back(pair(it->first,it->second));
        }
        
        auto comp=[&](const pair<char,int> &a,const pair<char,int> &b) {
            if(a.second>b.second) return true;
            else return false;
        };
        sort(v.begin(),v.end(),comp);
        
        string str="";
        for(auto &w:v)
            for(int i=0;i<w.second;i++) {
                str+=w.first;
            }
        
        return str;
    }
};

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/114638216