首页 > 学院 > 开发设计 > 正文

LeetCode-Q451-Sort Characters By Frequency

2019-11-06 08:50:08
字体:
来源:转载
供稿:网友

最近加入了一个每日一题的刷题群,在上面领教了很多大牛的思路和代码,觉得获益颇丰,自己也通过学习大牛的代码来总结。


自己思路 1、利用字典建立哈希表,遍历字符串记录每个字符的出现的次数。 2、对字典进行排序 3、依次输出频数从大到小的字符拼接成结果输出。

参考 在建立hash_map之后,可不用对字典进行排序(增加时间复杂度)。

代码

class Solution(object): def frequencySort(self,s): hash_map = {} res = "" #建立hash_map for char in s: if char not in hash_map: hash_map[char] = s.count(char) #不断找出hash_map中频次最高的字符,拼接后pop while(hash_map): max_frequency = max(hash_map.values()) index = list(hash_map.keys())[list(hash_map.values()).index(max_frequency)] res += index*max_frequency hash_map.pop(index) return res总结 除了哈希表的方法,还有桶排序和堆排序(建立最大堆)的方法。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表