最近加入了一个每日一题的刷题群,在上面领教了很多大牛的思路和代码,觉得获益颇丰,自己也通过学习大牛的代码来总结。
参考 在建立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总结 除了哈希表的方法,还有桶排序和堆排序(建立最大堆)的方法。新闻热点
疑难解答