一.题目:
给一个字符串,将它按照字母的个数降序排列.
二.解题思路:
首先统计字符串中每个字母的个数,然后将键和值放入到堆中,这里注意细节是将值放在前面,这样堆中会默认根据值的大小来建立堆.
其实还有一种简单的方法,即利用collections.Counter(s).most_common()这一方法直接得到按个数排列的列表.
代码如下:
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
#利用Counter自带的方法most_common
# count = collections.Counter(s).most_common()
# return "".join(c * t for c,t in count)
count = dict(collections.Counter(s))
heap = []
for i,j in count.items():
heapq.heappush(heap, (-j,i))
result = ""
while heap:
value,key = heapq.heappop(heap)
result += key * (-value)
return result