-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathSort_Characters_By_Frequency.cpp
38 lines (38 loc) · 1.17 KB
/
Sort_Characters_By_Frequency.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
class Solution {
public:
string frequencySort(string s) {
int n = s.length();
const int MAX_CHAR = 256;
vector<int> freq(MAX_CHAR, 0);
for(int i = 0 ; i < n; ++i) {
freq[s[i]]++;
}
#if 0
// bucket sort
vector<vector<int>> bucket(n + 1);
for (int i = 0; i < MAX_CHAR; i++) {
bucket[freq[i]].push_back(i);
}
string result = "";
for (int i = bucket.size() - 1; i > 0; i--) {
for (auto ch : bucket[i]) {
result += string(i, ch);
}
}
#endif
// auto compare = [] (pair<int, int> const& lhs, pair<int, int> const& rhs) -> bool const { return lhs.first < rhs.first; };
// priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(compare)> Q(compare);
priority_queue<pair<int, int>> Q;
for(int i = 0 ; i < MAX_CHAR; ++i) {
if(freq[i] > 0) {
Q.push({freq[i], i});
}
}
string result = "";
while(!Q.empty()) {
result += string(Q.top().first, Q.top().second);
Q.pop();
}
return result;
}
};