LeetCode 451 Sort Characters By Frequency (Python)

Posted by 小明MaxMing on May 22, 2020

题目

Given a string, sort it in decreasing order based on the frequency of characters.

解题思路

使用一个计数器,然后按频率从大到小排序,再拼回去

代码

from collections import Counter
class Solution:
    def frequencySort(self, s: str) -> str:
        return ''.join(k * v for k, v in sorted(Counter(s).items(), key=lambda x: x[1], reverse=True))

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅