问题描述:
Given a string, sort it in decreasing order based on the frequency of characters.
Example 1:
Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
Example 2:
Input: "cccaaa" Output: "cccaaa" Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. Note that "cacaca" is incorrect, as the same characters must be together.
Example 3:
Input: "Aabb" Output: "bbAa" Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters.
思路:这道题思路还是比较普通的,没什么tricks,首先用一个dict统计字符出现的频率,然后把dict根据value值排序得到r,r的格式就像这样['e':2,'t':1,'r':1],然后按顺序拼拼接str返回即可
class Solution(object):
def frequencySort(self, s):d = {}
for c in s:
if c in d:
d[c] += 1
else:
d[c] = 1
print(d)
r = sorted(d.items(),key=lambda item:item[1],reverse=True)
s=''
for i in r:
s+=(i[0]*i[1])
return s