我是靠谱客的博主 内向麦片,最近开发中收集的这篇文章主要介绍[LeetCode]Sort Characters By Frequency@Python,觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
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
最后
以上就是内向麦片为你收集整理的[LeetCode]Sort Characters By Frequency@Python的全部内容,希望文章能够帮你解决[LeetCode]Sort Characters By Frequency@Python所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复