Skip to content

Commit eacff63

Browse files
committed
Sort Characters By Frequency
1 parent 95df81b commit eacff63

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

451-sort-characters-by-frequency.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/sort-characters-by-frequency/
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+
Output:
10+
"eert"
11+
12+
Explanation:
13+
'e' appears twice while 'r' and 't' both appear once.
14+
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
15+
16+
Example 2:
17+
Input:
18+
"cccaaa"
19+
Output:
20+
"cccaaa"
21+
22+
Explanation:
23+
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
24+
Note that "cacaca" is incorrect, as the same characters must be together.
25+
26+
Example 3:
27+
Input:
28+
"Aabb"
29+
Output:
30+
"bbAa"
31+
32+
Explanation:
33+
"bbaA" is also a valid answer, but "Aabb" is incorrect.
34+
Note that 'A' and 'a' are treated as two different characters.
35+
"""
36+
class Solution:
37+
def frequencySort(self, s: str) -> str:
38+
d1, d2 = {}, {}
39+
for c in s:
40+
d1[c] = d1.get(c, 0) + 1
41+
42+
for k,v in d1.items():
43+
d2[v] = d2.get(v, '') + k*v
44+
45+
res = ''
46+
for i in range(len(s), -1, -1):
47+
if i in d2:
48+
res += d2[i]
49+
return res

0 commit comments

Comments
 (0)