class Solution {
public String frequencySort(String s) {
char[] str = s.toCharArray();
Map<Character,Integer> map = new HashMap<Character,Integer>();
List<Character> list = new ArrayList<Character>();//list排序比较简单
for(Character ch:str){
map.put(ch,map.getOrDefault(ch,0)+1);
list.add(ch);
}
Collections.sort(list, new Comparator<Character>() {
@Override
public int compare(Character o1, Character o2) {
return map.get(o2)-map.get(o1);//大于1 要交换
}
});
StringBuilder stringBuilder = new StringBuilder();//字符串和字符数组转换中经常用到
for(Character ch:list){
while(map.get(ch)>0){
stringBuilder.append(ch);
map.put(ch,map.get(ch)-1);
}
}
return stringBuilder.toString();
}
}