ProblemGiven 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]*r[i] return c[::-1] #(3)
(1) set(s) : not to count the frequency of the same characters repeatedly
- 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'.