451. 根据字符出现频率排序(中等,字符串)(12.23)

 给定一个字符串,请将字符串里的字符按照出现的频率降序排列。

示例 1:

输入:
"tree"

输出:
"eert"

解释:
'e'出现两次,'r'和't'都只出现一次。
因此'e'必须出现在'r'和't'之前。此外,"eetr"也是一个有效的答案。
class Solution(object):
    def frequencySort(self, s):
        """
        :type s: str
        :rtype: str
        """
        d = {}
        for i in range(len(s)):
            if s[i] in d:
                d[s[i]] += 1
            else:
                d[s[i]] = 1
        list1 = zip(d.values(),d.keys())
        list1.sort(reverse=True)
        res = ""
        for i in range(len(list1)):
            res += list1[i][1]*list1[i][0]
        return res
        

执行用时: 52 ms, 在Sort Characters By Frequency的Python提交中击败了81.58% 的用户 

class Solution(object):
    def frequencySort(self, s):
        """
        :type s: str
        :rtype: str
        """
        from collections import Counter
        count=collections.Counter(s).most_common()
        res=''
        for c,v in count:
            res+=c*v
        return res

Counter 集成于 dict 类,因此也可以使用字典的方法,此类返回一个以元素为 key 、元素个数为 value 的 Counter 对象集合

>>> from collections import Counter
>>> s = "hello pinsily"
>>> d = Counter(s)
>>> d
Counter({'l': 3, 'i': 2, 'h': 1, 'e': 1, 'o': 1, ' ': 1, 'p': 1, 'n': 1, 's': 1, 'y': 1})
elements()
返回一个迭代器

>>> d.elements()
<itertools.chain object at 0x0000019AC812BBA8>

# 可以进行打印和排序
>>> for i in d.elements():
...     	print(i)
...


most_common(n)
返回数量最多的前 n 个元素

>>> d.most_common(3)
[('l', 3), ('i', 2), ('h', 1)]
subtract([iterable-or-mapping])
相当于减法,调用这个方法的 Counter 会被覆盖掉

>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)
>>> c.subtract(d)
>>> c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
>>> d
Counter({'d': 4, 'c': 3, 'b': 2, 'a': 1})

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值