The title
Given a string, sort the characters in the string in descending order by frequency of occurrence.
Example 1: Input: "tree" Output: "eert" Explanation: 'e' occurs twice, 'r' and 't' occur only once. So 'e' must come before 'r' and 't'. In addition, "EETR" is also a valid answer. Example 2: Input: "ccCAaa" Output: "ccCAaa" Explanation: both 'c' and 'a' occur three times. Also, "aaaccc" is a valid answer. Note that "cacaca" is incorrect because the same letters must be placed 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.Copy the code
Their thinking
class Solution: def frequencySort(self, s: str) -> str: CountS = Counter(s) tupleList = [(x,y) for x,y in countS. Items ()] ## Sort (key=lambda x: x[1], reverse=True) resStr = "" for (val, count) in tuplelist.sort (key=lambda x: x[1], reverse=True) resStr += val*count return resStr if __name__ == '__main__': s = "tree" ret = Solution().frequencySort(s) print(ret)Copy the code