首页 > 编程语言 > 详细

leetcode-桶排序-451. 根据字符出现频率排序

时间:2021-08-11 09:18:32      阅读:30      评论:0      收藏:0      [点我收藏+]

 

技术分享图片

 

//  // 这种方法超时了
// 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;
    }
};

 

leetcode-桶排序-451. 根据字符出现频率排序

原文:https://www.cnblogs.com/ymec/p/15126414.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!