451. Sort Characters By Frequency
Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.
Return the sorted string. If there are multiple answers, return any of them.
Example 1:
Input: s = "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: s = "cccaaa"
Output: "aaaccc"
Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.
Note that "cacaca" is incorrect, as the same characters must be together.
Example 3:
Input: s = "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.
看到这个题确实不会做,看了一下答案。确实思考了很久才看懂答案,因为很多申明变量的时候还用的不熟练,Map-HashMap; List<> = new ArrayList[]; StringBuilder 等等。
首先是建立一个HashMap做Char 与出现次数的对应num;然后用一个桶Bucket的表List来装出现多少次的char。最后遍历这个桶,从前向后遍历然后用StringBuilder或者StringBuffer来储存,最后转换成String输出。学了python之后觉得这样好麻烦。
本文详细解析了一种字符串排序算法,该算法依据字符出现的频率进行降序排列。通过使用HashMap记录字符及其出现次数,并利用桶(Bucket)列表存放相同频率的字符,最终通过StringBuilder拼接得到结果字符串。

被折叠的 条评论
为什么被折叠?



