Sort Characters By Frequency
Given a string, sort it in decreasing order based on the frequency of characters.
Example
Input:
“tree”
Output:
“eert”
Explanation:
‘e’ appears twice while ‘r’ and ‘t’ both appear once.
So ‘e’ must appear before both ‘r’ and ‘t’. Therefore “eetr” is also a valid answer.
Solution
import collections
class Solution:
def frequencySort(self, s: str) -> str:
dic = collections.defaultdict(int)
for k in s:
dic[k]+=1
heap = [(-n, v) for v,n in dic.items()]
heapq.heapify(heap)
ret = ''
while heap:
n,v = heapq.heappop(heap)
ret += (-n)*v
return ret