leetcode 451. Sort Characters By Frequency(python)

261 阅读1分钟

描述

Given a string, sort it in decreasing order based on the frequency of characters.

Example 1:

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.


Example 2:

Input:
"cccaaa"

Output:
"cccaaa"

Explanation:
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.

Example 3:

Input:
"Aabb"

Output:
"bbAa"

Explanation:
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.

解析

根据题意,只需要使用内置的函数 Counter 来统计字符串中的字符及其出现频率,然后按照频率从大到小在遍历字符串的时候,将字符按照出现的频率依次拼接即可得到答案。

解答

class Solution(object):
    def frequencySort(self, s):
        """
        :type s: str
        :rtype: str
        """
        r = ""
        c = collections.Counter(s)
        for k,v in c.most_common(len(c)):
            r += k*v
        return r
        	      
		

运行结果

Runtime: 64 ms, faster than 38.84% of Python online submissions for Sort Characters By Frequency.
Memory Usage: 15.7 MB, less than 71.53% of Python online submissions for Sort Characters By Frequency.

原题链接:leetcode.com/problems/so…

您的支持是我最大的动力