<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
                

 

全部评论

相关推荐

nbdy:她的意思是,有的话就有,没有的话就没有
点赞 评论 收藏
分享
2024-11-20 17:56
已编辑
小米集团_测试开发(准入职员工)
双非坐过牢:非佬,可以啊10.28笔试,11.06评估11.11,11.12两面,11.19oc➕offer
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务