[Hash-medium] 451. Sort according to the frequency of characters

[Title]
Given a string, please arrange the characters in the string in descending order of frequency of appearance.
[Example 1]
Input:
"tree"
Output:
"eert"
Explanation:
'e' appears twice, and both'r' and't ' only appear once.
Therefore,'e' must appear before'r' and't'. In addition, "eetr" is also a valid answer.
[Example 2]
Input:
"cccaaa"
Output:
"cccaaa"
Explanation: Both'c' and'a
' appear three times. In addition, "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, because the same letters must be put together.
[Example 3]
Input:
"Aabb"
Output:
"bbAa"
Explanation:
In addition, "bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that'A' and'a' are considered two different characters.
[Code]
[Python]
Insert picture description here

class Solution:
    def frequencySort(self, s: str) -> str:
        cnt=dict(Counter(s))
        cnt=sorted(cnt.items(),key=lambda x:x[1],reverse=True)
        rs=[]
        for x in cnt:
            rs.extend([x[0]*x[1]])
        return "".join(rs)

[Method 2: Big top pile] The big guys in the comment area have learned how to solve it
Insert picture description here

class Solution:
    def frequencySort(self, s: str) -> str:
        # 大顶堆
        countFrequency = collections.defaultdict(int)
        for i in s:
            countFrequency[i] += 1
        lst = []
        heapq.heapify(lst)
        for i in countFrequency:
            print(i,countFrequency[i])
            for j in range(countFrequency[i]):
                heapq.heappush(lst, (-countFrequency[i], i))
        
        return ''.join([heapq.heappop(lst)[1] for _ in range(len(s))])

[Method 3: Bucket sorting]

class Solution:
    def frequencySort(self, s: str) -> str:
        # 桶排序
        ret = []
        countFrequency = collections.defaultdict(int)
        for i in s:
            countFrequency[i] += 1
        buckets = [[] for _ in range(len(s) + 1)]
        for i in countFrequency:
            buckets[countFrequency[i]].extend(i*countFrequency[i])
        for i in buckets[::-1]:
            if(i):
                ret.extend(i)
        return ''.join(ret)

Guess you like

Origin blog.csdn.net/kz_java/article/details/114730571