Sort character by frequency

注意字符串的操作,这道题就是把所有的字符统计起来,然后每次拼接找最大值

 


static int fast_io = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    return 0;
}();


class Solution {
public:
    string frequencySort(string s) {
        map<char, int> freq;
        for(char c: s){
            if(freq.find(c) == freq.end())
                freq[c] = 1;
            else 
                freq[c] += 1;
        }
        using Pair = pair<char, int>;
        auto cmp = [](Pair x, Pair y){ return x.second < y.second;};
        using Heap = priority_queue<Pair, vector<Pair>, decltype(cmp)>;
        Heap heap(cmp);
        for(auto item = freq.begin(); item != freq.end(); item++){
            heap.push(*item);
        }
        string result = "";
        while(!heap.empty()){
            result += string(heap.top().second, heap.top().first);
            heap.pop();
        }
        return result;
    }
};

找一个代码比较简洁的答案:

注意append以及char的定义域只有128个数等等。另外注意pair的初始化等等,都需要积累。

class Solution {
public:
    string frequencySort(string s) {
        vector<int> freq(128, 0);
        for(auto ch: s) freq[ch]++;
        priority_queue<pair<int, char>> pq;
        for(int i = 0; i < 128; i++) {
            if(freq[i] > 0) pq.push({freq[i], i});
        }
        string res("");
        while(!pq.empty()) {
            auto p = pq.top();
            pq.pop();
            res.append(p.first, p.second);
        }
        
        return res;
        
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值