451. Sort Characters By Frequency**

​https://leetcode.com/problems/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.

C++ 实现 1

使用哈希表以及最大堆.

class Solution {
private:
struct Comp {
bool operator()(const pair<char, int> &p, const pair<char, int> &q) {
return p.second < q.second;
}
};
public:
string frequencySort(string s) {
unordered_map<char, int> record;
priority_queue<pair<char, int>, vector<pair<char, int>>, Comp> q;
for (auto &c : s) record[c] ++;
for (auto &p : record) q.push(p);
string res;
while (!q.empty()) {
auto p = q.top();
q.pop();
res += string(p.second, p.first);
}
return res;
}
};

C++ 实现 2

两年前写的, 估计是认为 s 中的字符的频率不能超过 s 本身的大小, 所以用数组来记录.

class Solution {
public:
string frequencySort(string s) {
if (s.empty())
return s;

unordered_map<char, int> freq;
for (const auto &c : s)
freq[c] ++;

vector<string> records(s.size() + 1, "");
for (auto iter = freq.begin(); iter != freq.end(); ++iter) {
char c = iter->first;
int n = iter->second;
records[n].append(n, c);
}

string res;
for (int i = s.size(); i >= 0; --i) {
if (!records[i].empty())
res += records[i];
}
return res;
}
};