451. Sort Characters By Frequency
题目链接:https://leetcode.com/problems...
hashmap求frequency加排序,排序可以用bucket sort or heap sort。
bucket sort:
public class Solution {
public String frequencySort(String s) {
Map<Character, Integer> map = new HashMap();
int max = 0;
for(char c : s.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
max = Math.max(map.get(c), max);
}
List<Character>[] bucket = new List[max + 1];
int count = 0;
for(char c : map.keySet()) {
int index = map.get(c);
if(bucket[index] == null) bucket[index] = new ArrayList();
bucket[index].add(c);
count++;
}
StringBuilder sb = new StringBuilder();
sb.append("");
for(int i = bucket.length-1; i >= 0; i--) {
if(bucket[i] != null) {
for(char c : bucket[i]) {
for(int j = 0; j < i; j++) sb.append(c);
count--;
}
if(count == 0) break;
}
}
return sb.toString();
}
}
heap sort参考discussion:
https://discuss.leetcode.com/...
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。