Leetcode_Python 451 根据字符出现频率排序_hash

解题思路

此题的步骤

  1. 定义一个哈希字典,计算每个元素个数
  2. value的大小,对字典进行重排序
  3. 解析成字符串形式

代码

class Solution:
    def frequencySort(self, s: str) -> str:
        Hash = {i:0 for i in set(s)}
        for i in s:
            Hash["%s"%i] += 1
        dict= sorted(Hash.items(), key=lambda d:d[1], reverse = True)
        str1 = ""
        for character,num in dict:
            str1 += character * num
        return str1