-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.cpp
More file actions
75 lines (64 loc) · 1.71 KB
/
solution.cpp
File metadata and controls
75 lines (64 loc) · 1.71 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//
// Created by mingyi on 18.04.20.
//
#include <string>
#include <unordered_map>
#include <map>
#include <queue>
#include <cassert>
#include <sstream>
#include <iostream>
using namespace std;
string frequencySortHeap(string s) {
// count
unordered_map<char, int> freqMap;
for (const auto &c : s) {
freqMap[c]++;
}
// heapify
priority_queue<pair<int, char>> freqPQ; // (count, letter)
for (const auto &p : freqMap) {
freqPQ.push({p.second, p.first});
}
// get s
stringstream ss;
while (!freqPQ.empty()) {
auto p = freqPQ.top();
for (int i = 0; i < p.first; i++) {
ss << p.second;
}
freqPQ.pop();
}
return ss.str();
}
string frequencySortMap(string s) {
// count
unordered_map<char, int> letterFreqMap;
for (const auto &c : s) {
letterFreqMap[c]++;
}
// ordered map
map<int, vector<char>, greater<>> freqLetterMap;
for (const auto &p : letterFreqMap) {
freqLetterMap[p.second].push_back(p.first);
}
// get s
stringstream ss;
for (const auto &p : freqLetterMap) {
for (const auto &c : p.second) {
for (int i = 0; i < p.first; i++) {
ss << c;
}
}
}
return ss.str();
}
int main() {
assert("eetr" == frequencySortHeap("tree") || "eert" == frequencySortHeap("tree"));
assert("cccaaa" == frequencySortHeap("cccaaa") || "aaaccc" == frequencySortHeap("cccaaa"));
assert("bbAa" == frequencySortHeap("Aabb") || "bbaA" == frequencySortHeap("Aabb"));
assert("eetr" == frequencySortMap("tree") || "eert" == frequencySortMap("tree"));
assert("cccaaa" == frequencySortMap("cccaaa") || "aaaccc" == frequencySortMap("cccaaa"));
assert("bbAa" == frequencySortMap("Aabb") || "bbaA" == frequencySortMap("Aabb"));
return 0;
}