-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathFrequency.cpp
More file actions
39 lines (33 loc) · 930 Bytes
/
Frequency.cpp
File metadata and controls
39 lines (33 loc) · 930 Bytes
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
class Solution
{
public:
string FrequentCharacter(string str)
{
int n = str.length();
// If the string is empty return empty string
if (n == 0)
return "";
// Store the Frequency of each character in HashMap
unordered_map<char, int> freq;
for (auto &x : str)
freq[x]++;
// Store the frequency and character value in vector and sort it
vector<pair<int, char>> res;
for (auto &[key, val] : freq)
{
res.push_back({val, key});
}
sort(res.begin(), res.end(), greater<int>());
//Iterate through the Vector of pair and store the character value in the string ans
string ans = "";
for (auto &x : res)
{
while (x.first > 0)
{
ans += x.second;
x.first--;
}
}
return ans;
}
};