class Solution {
public String frequencySort(String s) {
//使用字典统计每个元素的个数
HashMap<Character,Integer> map = new HashMap<>();
for(char chr : s.toCharArray() ){
if(map.containsKey(chr)){
map.put(chr,map.get(chr)+1);
}
else{
map.put(chr,1);
}
}
//建立大根堆
PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>((e1, e2) -> e2.getValue() - e1.getValue());
//按照次数建立大根堆
pq.addAll(map.entrySet());
StringBuilder ans = new StringBuilder(s.length());
while(!pq.isEmpty()){
Map.Entry<Character,Integer> entry = pq.poll();
for(int i = 0 ;i < entry.getValue();i++){
ans.append(entry.getKey());
}
}
return ans.toString();
}
}