# Sort by character occurrence frequency 451

2022-04-23 16:02:00

### 451. Sort the characters according to their frequency of occurrence

• Question no ： Power button 451
• Knowledge point ： Hashtable , Count
• Goal completion ：25/150
• summary
stem ：

Ideas ：

• 1. First save the letter in the string and the number of times the letter appears in the dictionary `hashmap` in
• 2. then `hashmap` The letter stored in and the number of times the letter appears are transferred to the list `res` in , It is convenient to sort the number of occurrences from more to less , After finishing the sequence ,`res` According to the number of letters in the order from high to low
• 3. Re traversal `res`, Put each letter `y[0]` stay `ans` The number of times the letter appears is appended to the `y[1]` Time
``````class Solution:
def frequencySort(self, s: str) -> str:
hashmap = {
}
for x in s:
if x in hashmap:
hashmap[x] += 1
else:
hashmap[x] = 1
res = []
for key, value in hashmap.items():
res.append([key, value])
res.sort(key=lambda arr:arr[1], reverse=True)

ans = ''
for y in res:
for i in range(y[1]):
ans += (y[0])
return ans

``````

https://yzsam.com/2022/04/202204231558306122.html