Sort Characters By Frequency 题解

451. Sort Characters By Frequency


题目描述:

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

Example 1:

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.

Example 2:

Input:
"cccaaa"

Output:
"cccaaa"

Explanation:
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.

Example 3:

Input:
"Aabb"

Output:
"bbAa"

Explanation:
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.


题目链接:451. Sort Characters By Frequency


算法描述:

根据题意,给出一个字符串,我们将对它进行排序,按照字符串中各个字符的出现频率递减排序,出现次数越少排在越后面,最后返回一个结果字符串。

首先,我们将定义一个 map容器,map可以提供一对一的数据映射能力(其中第一个可以称之为关键字,每个关键字只能在map中出现一次,第二个可以称之为映射的值,即该关键字的值),由于map的这个特性,我们在这道题中可以充分的运用以方便统计给出字符串中各个字符的出现个数。完成映射之后,我们构造临时容器 temp ,将map中的元素填装进 vector 。

第二步,我们应用 sort 函数对 vector 进行排序,按照字符在字符串中出现的次数递减排序。

最后,我们根据出现次数,构造字符串。


代码:

class Solution {
public:
    string frequencySort(string s) {
        string ans;
        vector<pair<char,int>> temp;
        map<char,int> m;
        for(int i=0; i<s.size(); i++){
            m[s[i]]++;
        }
        for(auto it:m){
            pair<char,int> p(it.first,it.second);
            temp.push_back(p);
            
        }
        sort(temp.begin(),temp.end(),[](pair<char,int> a, pair<char,int> b){
            return a.second>b.second;
        });
        
        for(int i=0; i<temp.size(); i++){
            string str(temp[i].second,temp[i].first);
            ans+=str;
        }
        return ans;
    }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值