
// // 这种方法超时了
// class Solution {
// public:
// static bool cmp(pair <char,int> &a, pair <char,int> &b){
// return a.second > b.second;
// }
// string tostr(char a, int b){
// string res;
// for(int i = 0; i < b; i++){
// res = res + a;
// }
// return res;
// }
// string frequencySort(string s) {
// unordered_map <char,int> un_map;
// for(int i = 0; i < s.size(); i++){
// un_map[s[i]]++;
// }
// string res;
// vector<pair<char,int>> v;
// for(auto it = un_map.begin(); it!=un_map.end();it++){
// // res += tostr
// v.push_back(pair<char,int>(it->first, it->second));
// }
// sort(v.begin(),v.end(),cmp);
// for(int i = 0; i < v.size(); i++){
// res += tostr(v[i].first, v[i].second);
// }
// return res;
// }
// };
// 这种方法超时了
class Solution {
public:
string frequencySort(string s) {
unordered_map <char,int> un_map;
int maxsize = 0;
for(int i = 0; i < s.size(); i++){
un_map[s[i]]++;
maxsize =max(maxsize, un_map[s[i]]);
}
vector<string> bucket(maxsize+1);
string res;
//cout<<"maxsize::"<<maxsize<<endl;
for(auto it = un_map.begin(); it!=un_map.end();it++){
// 会存在2 对应的字母为a b 即a, b出现次数都为2
bucket[it->second].push_back(it->first);
}
// 将出现的频次作为下标,从大到小遍历下标,自然就可以排序
for(int i = bucket.size()-1; i >= 0; i--){
string tmp = bucket[i];
for(auto ch:tmp)
for(int j = 0; j < i; j++){
res.push_back(ch);
}
}
return res;
}
};