给定一个字符串,请将字符串里的字符按照出现的频率降序排列。java
示例 1:app
输入:
“tree”ide
输出:
“eert”ui
解释:
'e’出现两次,'r’和’t’都只出现一次。
所以’e’必须出如今’r’和’t’以前。此外,"eetr"也是一个有效的答案。
示例 2:spa
输入:
“cccaaa”code
输出:
“cccaaa”排序
解释:
'c’和’a’都出现三次。此外,"aaaccc"也是有效的答案。
注意"cacaca"是不正确的,由于相同的字母必须放在一块儿。
示例 3:字符串
输入:
“Aabb”get
输出:
“bbAa”it
解释:
此外,"bbaA"也是一个有效的答案,但"Aabb"是不正确的。
注意’A’和’a’被认为是两种不一样的字符。
class Solution { public String frequencySort(String s) { int[] map = new int[128]; for (char ch : s.toCharArray()) { map[ch]++; } int target = -1; StringBuilder ans = new StringBuilder(); while ((target = getChar(map)) > 0) { while (map[target]-- > 0) { ans.append((char) target); } } return ans.toString(); } private int getChar(int[] counting) { int idx = -1, max = 0; for (int i = 0; i < 128; i++) { if (counting[i] > max) { max = counting[idx = i]; } } return idx; } }