-
题目链接 https://leetcode-cn.com/problems/sort-characters-by-frequency/
-
题目描述
- 给定一个字符串,请将字符串里的字符按照出现的频率降序排列。
-
输入: "tree" 输出: "eert"
-
输入: "cccaaa" 输出:
-
解题思路
- 统计词频 + 基于词频排序
-
代码
- python
class Solution: def frequencySort(self, s: str) -> str: if not s: return s from collections import Counter from functools import reduce c = Counter(s) return "".join(reduce(lambda a, b:a + b, [[key] * c[key] for key in sorted(list(c.keys()), key=lambda a: c[a], reverse=True)]))
- python
leetcode 451. 根据字符出现频率排序
最新推荐文章于 2022-04-06 14:46:44 发布