-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path451. Sort Characters By Frequency.cpp
64 lines (44 loc) · 1.17 KB
/
451. 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
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
class Solution {
public:
string frequencySort(string s) {
string res = "";
if(s.empty())
return res;
vector<pair<int,char> > f(256,{0,0});
int n = s.length();
for (int i = 0;i<n;++i) {
++f[s[i]].first;
f[s[i]].second = s[i];
}
sort(f.begin(),f.end());
reverse(f.begin(),f.end());
for (int i = 0;i<f.size(); ++i) {
if(f[i].first < 1)
break;
while(f[i].first--)
res += f[i].second;
}
return res;
}
};
----------
class Solution {
public:
string frequencySort(string s) {
unordered_map<char, int> m;
string res = "";
for(int i = 0;i<s.length(); ++i) {
m[s[i]]++;
}
vector<pair<char, int> > v;
for(auto i:m) {
v.push_back(make_pair(i.first, i.second));
}
sort(v.begin(), v.end(), [] (const pair<char, int> &i1, const pair<char, int> &i2) {return i1.second > i2.second;});
for(auto i: v) {
while(i.second--)
res += i.first;
}
return res;
}
};