Python 3 Solution & Explanation - 41ms, beats 100%


  • 0
    P

    Problem

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

    Solution & Explanation

    class Solution(object):
        def frequencySort(self, s):
            a = list(set(s))  #(1)  
            r = sorted([(s.count(a[i]), a[i]) for i in range(len(a))]) #(2)
            c = ""  
            for i in range(len(r)):
                c = c + r[i][0]*r[i][1] 
            return c[::-1] #(3)
    

    (1) set(s) : not to count the frequency of the same characters repeatedly

    (2)

    • List 'a' consists of single characters. So, count each items of list 'a' in the original list 's'.
    • Make each items tuple (frequency, item) and sort by the first item of tuple - frequency - in an increasing order.

    (3) Problem says the answer is a string in decreasing order based on the frequency of characters. Therefore, return reversed 'c'.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.