leetCode题解之根据字符出现的频率排序

1、题目描述

     

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.


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.

题目意思是将一个输入string,按照其中每个字符出现的 频率进行重新排序,频率高的排在前面,频率低的排在后面,出现次数相同的则不做要求。

2、问题分析
统计字符串中每一个字符出现的次数,一般都会使用 hash 表的方法。本题中首先使用一个 无序的 unordered_map 将 每个字符出现的次数统计出来,
想对字符按照顺序排序有多种方法,我选择使用 multimap 的方法,这个 hasp表的优点在于,key 可以重复出现,而且是根据键的值自动进行排序的。
思路是将第一步得到的 unordered_map 中的每一项,将key 和 value 换个位置,这样得到的multimap 就是自动排好序的。然后对 multimap 进行输出,拼接成字符串,最后对字符串使用 reserve()方法即可。

3、代码

 1  unordered_map<char,int>  m;
 2         
 3         for(  auto &c : s )
 4             m[c]++;
 5         
 6         multimap<int ,char> m1;
 7         
 8         
 9         for( auto& itr : m)
10         {
11             m1.insert( make_pair(itr.second,itr.first) );
12         }
13         
14         string s_out;
15         for(auto& itr :m1)
16         {
17             int n = itr.first ;
18             while(n)
19             {
20                 s_out.push_back(itr.second);
21                 n--;
22             }
23                 
24         }
25       
26         reverse(s_out.begin(), s_out.end());
27         return s_out;
28 }

 



转载于:https://www.cnblogs.com/wangxiaoyong/p/8659863.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值