题目:
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.
代码:
别看题目很长,其实就是: 给定一个字符串,找出里面每个字符出现的频率,按频率从从大到小排序。
想了半天,觉得怎么都是遍历一遍,记录并求出每个字符出现的次数,之后排序。
可是,网上查了一下,才知道python原来是那么的牛B,有这样一个函数:
看举例子就明白了,而且顺序都排好了,是不是很流弊!
这个函数在collection模块的Counter类中:
于是,看似很复杂的题目,用python写只剩一句话了:
class Solution(object):
def frequencySort(self, s):
"""
:type s: str
:rtype: str
"""
#print (collections.Counter(s).most_common())
return ''.join(c * num for c, num in collections.Counter(s).most_common())
当然,我总觉得这样自身没什么思考。不过有时候快速开发,解决问题,确实更重要!