1+ ##==================================
2+ ## Leetcode May Challenge
3+ ## Username: Vanditg
4+ ## Year: 2020
5+ ## Problem: 22
6+ ## Problem Name: Sort Characters By Frequency
7+ ##===================================
8+ #
9+ #Given a string, sort it in decreasing order based on the frequency of characters.
10+ #
11+ #Example 1:
12+ #
13+ #Input:
14+ #"tree"
15+ #
16+ #Output:
17+ #"eert"
18+ #
19+ #Explanation:
20+ #'e' appears twice while 'r' and 't' both appear once.
21+ #So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
22+ #Example 2:
23+ #
24+ #Input:
25+ #"cccaaa"
26+ #
27+ #Output:
28+ #"cccaaa"
29+ #
30+ #Explanation:
31+ #Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
32+ #Note that "cacaca" is incorrect, as the same characters must be together.
33+ #Example 3:
34+ #
35+ #Input:
36+ #"Aabb"
37+ #
38+ #Output:
39+ #"bbAa"
40+ #
41+ #Explanation:
42+ #"bbaA" is also a valid answer, but "Aabb" is incorrect.
43+ #Note that 'A' and 'a' are treated as two different characters.
44+ class Solution :
45+ def frequencySort (self , s ):
46+ tmp , res = {}, '' #Initialize tmp dictionary and res empty string
47+ for i in s : #Loop through string s
48+ if i in tmp : #Condition-check: If char i is in tmp dictionary
49+ tmp [i ] += 1 #We update the value of that character
50+ else : #Condition-check: Else
51+ tmp [i ] = 1 #We update that character in dictionary
52+ s = sorted (tmp , key = lambda i : tmp [i ], reverse = True ) #We sort the dictionary's key value in reverse order based on the frequency
53+ for char in s : #Loop through our sorted tring
54+ res += char * tmp [char ] #We multiply our character with the frequency and update in the string s
55+ return res #We return string res
0 commit comments