leetcode 451 Sort Characters By Frequency

1. 

class Solution {
public:
    string frequencySort(string s) {
        map<char,int> m;
        for(auto& c:s) {
            ++m[c];
        }
        string str;char c;
        while((c=get_max(m))) {
            if(!m[c]) break;
            while(m[c]--!=0) str.push_back(c);
            m.erase(c);
        }
        return str;
    }
    char get_max(map<char,int>& m) {
        if(m.empty()) return NULL;
        auto ite=m.begin(),end=m.end();
        char c=ite->first;
        for(++ite;ite!=end;++ite) {
            if(ite->second>m[c]) c=ite->first;
        }
        return c;
    }
};

猜你喜欢

转载自www.cnblogs.com/LiuQiujie/p/13190707.html