Leetcode-451

451. 根据字符出现频率排序

题目

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
示例 1:
输入:
"tree"

输出:
"eert"

解释:
'e'出现两次,'r'和't'都只出现一次。
因此'e'必须出现在'r'和't'之前。此外,"eetr"也是一个有效的答案。

示例 2:
输入:
"cccaaa"

输出:
"cccaaa"

解释:
'c'和'a'都出现三次。此外,"aaaccc"也是有效的答案。
注意"cacaca"是不正确的,因为相同的字母必须放在一起。
示例 3:

输入:
"Aabb"

输出:
"bbAa"

解释:
此外,"bbaA"也是一个有效的答案,但"Aabb"是不正确的。
注意'A'和'a'被认为是两种不同的字符。

方法

方法1:采用堆heap & collections.Counter()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
from heapq import *
from collections import Counter

chars=Counter(s)
heap=[]
for key in chars:
heappush(heap,(chars[key],key))

output=''
while heap:
char = heappop(heap)
output+=char[1]*char[0]
return output[::-1]

方法2:堆heap

  • collections.Counter().most_common([n])
    Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter. Elements with equal counts are ordered arbitrarily:
    1
    2
    >>> Counter('abracadabra').most_common(3)
    [('a', 5), ('r', 2), ('b', 2)]
1
2
3
4
5
6
7
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
return ''.join([char*freq for char,freq in collections.Counter(s).most_common()])

方法3:collections.Counter & sorted

1
2
3
4
5
6
7
8
9
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
chars = collections.Counter(s)
chars=sorted(chars.items(),key=lambda c:c[1],reverse=True)
return ''.join([char[1]*char[0] for char in chars])

参考资料