-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort_characters_by_frequency.cpp
More file actions
82 lines (76 loc) · 2.03 KB
/
sort_characters_by_frequency.cpp
File metadata and controls
82 lines (76 loc) · 2.03 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
76
77
78
79
80
81
82
/*
* =====================================================================================
*
* Filename: sort_characters_by_frequency.cpp
*
* Description: 451. Sort Characters By Frequency
* https://leetcode.com/problems/sort-characters-by-frequency/
*
* Version: 1.0
* Created: 02/22/2022 22:11:17
* Revision: none
* Compiler: gcc
*
* Author: xianfeng.zhu@gmail.com
* Organization:
*
* =====================================================================================
*/
#include <algorithm>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
// Hash table without sort
class Solution1 {
public:
std::string frequencySort(const std::string& s) {
// Count frequency
std::unordered_map<char, int> freq;
for (const char c : s) {
freq[c]++;
}
// Gather characters with same frequency
std::vector<std::string> bucket(s.size() + 1);
for (const auto& item : freq) {
bucket[item.second].append(1, item.first);
}
// Assemble sorted string
std::string res;
for (int i = bucket.size() - 1; i > 0; i--) {
if (bucket[i].empty()) {
continue;
}
for (char c : bucket[i]) {
res.append(i, c);
}
}
return res;
}
};
// Hash table with sort
class Solution2 {
public:
std::string frequencySort(std::string s) {
std::vector<int> counts(128, 0);
for (const char c : s) {
counts[c]++;
}
std::sort(s.begin(), s.end(), [&](const char a, const char b) -> bool {
return counts[a] > counts[b] || (counts[a] == counts[b] && a < b);
});
return s;
}
};
TEST(Solution, frequencySort) {
std::vector<std::pair<std::string, std::string>> cases = {
std::make_pair("tree", "eert"),
std::make_pair("cccaaa", "aaaccc"),
};
for (auto& c : cases) {
EXPECT_EQ(Solution1().frequencySort(c.first), c.second);
EXPECT_EQ(Solution2().frequencySort(c.first), c.second);
}
}