Skip to content

Commit ebec059

Browse files
Create Day 22 Sort Characters By Frequency.cpp
1 parent 49d0896 commit ebec059

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
PROBLEM:
2+
3+
4+
Given a string, sort it in decreasing order based on the frequency of characters.
5+
6+
Example 1:
7+
Input:
8+
"tree"
9+
10+
Output:
11+
"eert"
12+
13+
Explanation:
14+
'e' appears twice while 'r' and 't' both appear once.
15+
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
16+
17+
Example 2:
18+
Input:
19+
"cccaaa"
20+
21+
Output:
22+
"cccaaa"
23+
24+
Explanation:
25+
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
26+
Note that "cacaca" is incorrect, as the same characters must be together.
27+
28+
Example 3:
29+
Input:
30+
"Aabb"
31+
32+
Output:
33+
"bbAa"
34+
35+
Explanation:
36+
"bbaA" is also a valid answer, but "Aabb" is incorrect.
37+
Note that 'A' and 'a' are treated as two different characters.
38+
39+
40+
41+
42+
SOLUTION:
43+
44+
45+
46+
unordered_map<char,int> m;
47+
48+
class Solution {
49+
public:
50+
51+
bool static cmp(char a,char b)
52+
{
53+
return (m[a]>m[b] || (m[a]==m[b] && a<b));
54+
}
55+
56+
string frequencySort(string s) {
57+
58+
int i,n;
59+
n=s.length();
60+
m.clear();
61+
62+
for(i=0;i<n;i++)
63+
{
64+
m[s[i]]++;
65+
}
66+
67+
// for(auto k:m)
68+
// {
69+
// cout<<k.first<<" "<<k.second<<endl;
70+
// }
71+
72+
sort(s.begin(),s.end(),cmp);
73+
74+
75+
76+
return s;
77+
}
78+
};

0 commit comments

Comments
 (0)