leet_451_sort_characters_by_frequency(按字符出现频率排序)
程序员文章站
2022-03-03 08:41:23
...
- leet_code:地址
- 问题描述:给定一个字符串,按照字符出现频率降序排序输出。
- 输入输出样例:
- Input:
“tree” - Output:
“eert”
- Input:
- 相似题目:leet_347_top_k_frequent(前K个频率最大)
- 解题思路:桶排序
- c++ 代码实现
- 代码注意:
- 涉及到vector初始化问题
- 涉及到string的append方法使用问题
- 代码注意:
class Solution
{
public:
string frequencySort(string s)
{
unordered_map<char, int> freq;
string res;
for (char c : s)
freq[c]++;
vector<string> bucket(freq.size() + 1, "");//or not give the second parameter by default
for (auto m : freq)
bucket[m.second].append(m.second, m.first);//pay attention to the use of string's "append" function.
reverse(begin(bucket), end(bucket));
for (string s : bucket)
res += s;
return res;
}
};
主程序:
int main(int argc, char* argv[])
{
string s = "tree";
Solution solution;
string res = solution.frequencySort(s);
cout << "sorted result is:" << res << endl;
system("pause");
return 0;
}