Skip to content

Commit 5c0d4ea

Browse files
Add files via upload
1 parent af9e92c commit 5c0d4ea

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Runtime: 16 ms, faster than 74.99% of C++ online submissions for Sort Characters By Frequency.
2+
// Memory Usage: 10.6 MB, less than 82.35% of C++ online submissions for Sort Characters By Frequency.
3+
4+
struct cell
5+
{
6+
cell () : chr('x'), times(0) {}
7+
cell (char c, int t) : chr(c), times(t) {}
8+
char chr;
9+
int times;
10+
};
11+
12+
class Solution
13+
{
14+
public:
15+
string frequencySort(string s)
16+
{
17+
vector<cell> hashmap(128);
18+
for (int i = 0; i < 128; ++i)
19+
hashmap[i].chr = i;
20+
21+
for (char chr : s)
22+
++hashmap[chr].times;
23+
24+
auto comp = [](const cell& item1, const cell& item2){return item1.times > item2.times;};
25+
sort(hashmap.begin(), hashmap.end(), comp);
26+
27+
string res = "";
28+
for (auto item : hashmap)
29+
for (int i = 0; i < item.times; ++i)
30+
res += item.chr;
31+
32+
return res;
33+
}
34+
};

0 commit comments

Comments
 (0)