<span>leetcode-451 Sort Characters By Frequency</span>
Given a string, sort it in decreasing order based on the frequency of characters.
输入输出实例:
Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
一开始没有仔细看题,我看第一个输出以为还需要先按照字母进行排序,后面发现两种系统都会判定为正确的,导致多进行了一次排序。
class Solution: def frequencySort(self, s: str) -> str: dic = {} result = "" for i in s: if i in dic: dic[i] += 1 else: dic[i] = 1 d1 = [(k, dic[k]) for k in sorted(dic.keys(), reverse=True)] d1 = sorted(d1, key = lambda x:x[1], reverse=True) for i in range(len(d1)): for _ in range(d1[i][1]): result = result + d1[i][0] return result