728x90
https://leetcode.com/problems/sort-characters-by-frequency/
class Solution:
def frequencySort(self, s: str) -> str:
count = Counter(s) # char -> cnt
buckets = defaultdict(list) # frequency -> [char]
for char, cnt in count.items():
buckets[cnt].append(char)
res = []
for i in range(len(s), 0, -1):
for c in buckets[i]:
res.append(c * i)
return "".join(res)
bucket sort that have sparse key , but we can skip if key doesn't exist in buckets.
728x90
'Algorithm > NeetCode' 카테고리의 다른 글
Sequential Digits (0) | 2024.11.25 |
---|---|
Divide Array Into Arrays With Max Difference (0) | 2024.11.24 |
Minimum Number of Operations to Make Array Empty (0) | 2024.11.23 |
Convert an Array Into a 2D Array With Conditions (0) | 2024.11.22 |
Design a Food Rating System (0) | 2024.11.21 |