forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0451.cpp
54 lines (54 loc) · 1.18 KB
/
0451.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <string>
#include <queue>
#include <unordered_map>
using namespace std;
static int x = []() {std::ios::sync_with_stdio(false); cin.tie(0); return 0; }();
class Solution
{
public:
struct Ch
{
int key;
int val;
Ch(int key, int val):key(key), val(val){}
bool operator < (const Ch& other) const {
return val < other.val;
}
};
string frequencySort(string s)
{
unordered_map<char, int> str_map;
for (auto& i : s)
{
++str_map[i];
}
priority_queue<Ch> qChar;
for (int i = 0; i < 255; i++)
{
if (str_map[i])
{
Ch c(i, int(str_map[i]));
qChar.push(c);
}
}
string result;
while (!qChar.empty())
{
int key = qChar.top().key;
int val = qChar.top().val;
while (val--)
{
result.push_back((char)key);
}
qChar.pop();
}
return result;
}
};
int main()
{
string s = "cccaaa";
cout << Solution().frequencySort(s) << endl;
return 0;
}