Leetcode451. 对字符出现频率进行排序
2017-09-23 08:34
465 查看
Leetcode451. 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.
解题分析
通过上面几个例子我们可以发现,题目要求我们按照字符出现频率从高到低进行排序,大小写区分。看到字符出现频率,很自然地就想到用unordered_map哈希表来存储每个字符出现的次数。然后通过对整个哈希表进行排序,最后将其进行输出。但是这里有一个问题,就是stl的sort算法只能对线性序列容器进行排序(即vector,list,deque)。所以我们这里就要设法将存储在哈希表里面的内容转移到vector这些容器中了。这里由于哈希表存储的是key-value对,所以vector应该声明成pair某种模板类型,这样在vector中才能通过value找到相对应的key值。
在将键值对全部插入到vector之后,就要对value值进行排序了。stl的sort函数有三个参数,其中第三个参数是可选的,是一个返回值类型可转化为bool的函数,表示sort的方式。如果我们不传入第三个参数,那么sort完成后输出的结果就是按ascii值从小到大进行排序的结果。因此,在这里有必要传入第三个参数。
这里用到了c++11的lambda表达式,它是一种函数式编程的写法,其中[]表示要捕获的内容,()表示函数传入的参数。这里函数体内容就很简单了,只需比较两个参数对应的value值,这样我们就确定了sort排序的方式,问题就解决了。
源代码
class Solution { public: string frequencySort(string s) { string str = ""; unordered_map<char, int> iMap; vector<pair<char, int>> vtMap; for (int i = 0; i < s.size(); i++) { iMap[s[i]]++; } for (auto it = iMap.begin(); it != iMap.end(); it++) { vtMap.push_back(make_pair(it->first, it->second)); } sort(vtMap.begin(), vtMap.end(), [](const pair<int, int>& x, const pair<int, int>& y) -> int { return x.second > y.second; }); for (auto it = vtMap.begin(); it != vtMap.end(); it++) { for (int i = 0; i < it->second; i++) { str += it->first; } } return str; } };
以上是我对这道问题的一些想法,有问题还请在评论区讨论留言~
相关文章推荐
- [LeetCode] Sort Characters By Frequency 根据字符出现频率排序
- 赫夫曼树(一),对字符串中的字符出现频率进行设置权,并且根据权大小进行排序
- [LeetCode] 451. Sort Characters By Frequency 根据字符出现频率排序
- 针对一个文件 统计其中的单词和字符数 找出文件中出现次数最多的单词数 将文件中出现的单词按频率进行排序并输出
- 按字符出现频率对字符进行排序
- LeetCode 451. Sort Characters By Frequency (根据字符出现频率排序)
- 对字符串中字符出现的次数进行排序
- (使用STL自带的排序函数进行编程7.3.14)UVA 10062 Tell me the frequencies!(求一个字符出现的次数(包括字母和数字)&&按出现的次数降序)
- 将一段(英文)按照字符出现的频率进行倒序排列
- Leetcode 451. Sort Characters By Frequency 按频率对字符排序 解题报告
- Leetcode 451. Sort Characters By Frequency 按频率对字符排序
- 华为oj之字符统计(按出现次数由多到少的顺序进行输出)
- 按照查询结果中某列出现的次数进行排序的SQL语句
- 读取字符从控制台窗口,然后进行排序_v1_不能执行。
- 常见对象_把字符串中的字符进行排序案例
- 统计一个大小为30kb~300kb的文本中各单词出现的频率,并输出前十个单词和进行程序性能分析
- 【LeetCode】Merge Intervals 题解 利用Comparator进行排序
- 每天一道LeetCode-----给定字符串s和字符数组words,在s中找到words出现的位置,words内部字符串顺序无要求
- 使用插入排序算法对列表进行排序——Leetcode系列(五)
- LeetCode 问题难度,面试出现频率及问题相关数据结构和算法