class Solution {
public String frequencySort(String s) {
Map<Integer,List<Character>> map = new HashMap<>(); //排序
char[] chars = s.toCharArray();
Arrays.sort(chars);
int slow = 0,fast = 0;
while(fast < chars.length){
while(fast < chars.length && chars[fast] == chars[slow]){
fast++;
}
if(map.get(fast-slow) == null){
map.put(fast-slow,new ArrayList<>());
}
List<Character> charList = map.get(fast - slow);
charList.add(chars[slow]);
map.put(fast-slow,charList);
slow = fast; } //根据出现次序从大到小排序
StringBuilder sb = new StringBuilder();
List<Integer> keys = new ArrayList<>(map.keySet());
Collections.sort(keys, new Comparator<Integer>() {
@Override public int compare(Integer o1, Integer o2) {
return o2-o1;
} });
for(int key : keys){
List<Character> characterList = map.get(key);
for(char c : characterList){
int count = key;
while(count > 0){
sb.append(c); count--;
}
}
}
return sb.toString();
}
}