您的位置:首页 > 其它

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;
}
};


以上是我对这道问题的一些想法,有问题还请在评论区讨论留言~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐