【英文题目】(学习英语的同时,更能理解题意哟~)
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.
【中文题目】
给定一个字符串,请将字符串里的字符按照出现的频率降序排列。
示例 1:
输入:
"tree"
输出:
"eert"
解释:
'e'出现两次,'r'和't'都只出现一次。
因此'e'必须出现在'r'和't'之前。此外,"eetr"也是一个有效的答案。
【思路】
对所有字符计数,按照计数结果倒排即可。
(c++对map的排序也太复杂了吧)
【代码】
python版本
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++版本
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;
}
};