Skip to content

Latest commit

 

History

History
32 lines (22 loc) · 1001 Bytes

451.-sort-characters-by-frequency.md

File metadata and controls

32 lines (22 loc) · 1001 Bytes

451. Sort Characters By Frequency

  • Medium

  • Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.

    Return the sorted string. If there are multiple answers, return any of them.

Analysis

We will solve this by doint what the question tells us to do. First we record the frequency of the characters in a dictionary. Then we turn it into a list and sort it. Finally we build our answer based on that list.

class Solution:
    def frequencySort(self, s: str) -> str:
        def sort1(s):
            return s[1];
        
        
        dic=defaultdict(int)
        for char in s:
            dic[char]+=1
        occur=list(dic.items())
        occur.sort(key=sort1,reverse=True);
        
        ans=""
        for (i,j) in occur:
            ans+=i*j
            
        return ans