代码:
class Solution {
public String frequencySort(String s) {
Map<Character,Integer> map = new HashMap<>();
for( Character ch : s.toCharArray() ){
map.put(ch,map.getOrDefault(ch,0) + 1);
}
Character []chars = map.keySet().toArray(new Character[map.size()]);
// 根据出现次数进行排序
Arrays.sort(chars, new Comparator<Character>() {
@Override
public int compare(Character ch1, Character ch2) {
return map.get(ch1) > map.get(ch2) ? -1 :
map.get(ch1) == map.get(ch2) ? 0 : 1;
}
});
// 构造结果字符串
String res = "";
for( char ch : chars ){
int cnt = map.get(ch);
for( int i = 0; i < cnt; ++i ){
res += ch;
}
}
return res;
}
}