力扣题-12.1
[力扣刷题攻略] Re:从零开始的力扣刷题生活
力扣题1:451. 根据字符出现频率排序
解题思想:统计字符出现的个数,进行排序即可
class Solution(object):def frequencySort(self, s):""":type s: str:rtype: str"""char_count = {}for i in range(len(s)):if s[i] in char_count:char_count[s[i]] += 1else:char_count[s[i]] = 1sorted_char_count = OrderedDict(sorted(char_count.items(), key=lambda item: item[1], reverse=True))result = ''for char, count in sorted_char_count.items():result = result + char * countreturn result
class Solution {
public:string frequencySort(string s) {std::unordered_map<char, int> char_count;for (char c : s) {if (char_count.find(c) != char_count.end()) {char_count[c] += 1;} else {char_count[c] = 1;}}std::vector<std::pair<char, int>> char_freq_vec(char_count.begin(), char_count.end());std::sort(char_freq_vec.begin(), char_freq_vec.end(),[](const auto& a, const auto& b) {return a.second > b.second;});std::string result;for (const auto& p : char_freq_vec) {result += std::string(p.second, p.first);}return result;}
};