[LeetCode] Sort Characters By Frequency

451. Sort Characters By Frequency

Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.

Return the sorted string. If there are multiple answers, return any of them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
string frequencySort(string s) {
string res = "";
unordered_map<char, int> mp;
priority_queue<pair<int,char>> pq;
for(auto& ch : s) mp[ch]++;
for(auto& [k, v] : mp) pq.push({v, k});
while(!pq.empty()) {
auto [c, ch] = pq.top(); pq.pop();
res += string(c, ch);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/21/PS/LeetCode/sort-characters-by-frequency/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.