前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T40-根据字符出现频率排序

【leetcode刷题】T40-根据字符出现频率排序

作者头像
木又AI帮
修改2019-07-18 10:00:57
5870
修改2019-07-18 10:00:57
举报
文章被收录于专栏:木又AI帮

【英文题目】(学习英语的同时,更能理解题意哟~)

Given a string, sort it in decreasing order based on the frequency of characters.

Example 1:

代码语言:javascript
复制
Input:
"tree"

Output:
"eert"

Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

【中文题目】

给定一个字符串,请将字符串里的字符按照出现的频率降序排列。

示例 1:

代码语言:javascript
复制
输入:
"tree"

输出:
"eert"

解释:
'e'出现两次,'r'和't'都只出现一次。
因此'e'必须出现在'r'和't'之前。此外,"eetr"也是一个有效的答案。

【思路】

对所有字符计数,按照计数结果倒排即可。

(c++对map的排序也太复杂了吧)

【代码】

python版本

代码语言:javascript
复制
class Solution(object):
    def frequencySort(self, s):
        """
        :type s: str
        :rtype: str
        """
        d = {}
        for si in s:
            d[si] = d.get(si, ) + 
        ls = list(d.items())
        # 按照value排序
        ls.sort(key=lambda x:x[], reverse=True)
        res = []
        for lsi in ls:
            res.extend([lsi[] * lsi[]])
        return ''.join(res)

C++版本

代码语言:javascript
复制
typedef pair<char, int> PAIR;  

struct CmpByValue {  
    bool operator()(const PAIR& lhs, const PAIR& rhs) {  
        return lhs.second > rhs.second;  
    }  
};  

class Solution {
public:
    string frequencySort(string s) {
        map<char, int> d;
        for(int i=; i<s.size(); i++){
            d[s[i]]++;
        }
        // 繁琐的排序操作
        vector<PAIR> vec;
        for(map<char, int>::iterator it=d.begin(); it != d.end(); it++)
            vec.push_back({it->first, it->second});
        sort(vec.begin(), vec.end(), CmpByValue());

        string res = "";
        for(int i=; i<vec.size(); i++){
            for(int j=; j<vec[i].second; j++)
                res += vec[i].first;
        }
        return res;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-04-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档