image.png

解题思路

Map

  1. 先统计字符串s中各个字符的频率
  2. 自定义Item存储字符和对应的频率,然后根据字符频率创建优先队列
  3. 挨个从队列中取出元素Item,根据字符和频率拼接出结果
  1. public String frequencySort(String s) {
  2. class Item{
  3. public Item(Character character, Integer count) {
  4. this.character = character;
  5. this.count = count;
  6. }
  7. private Character character;
  8. private int count;
  9. }
  10. Map<Character,Integer> map = new HashMap<>();
  11. PriorityQueue<Item> priorityQueue = new PriorityQueue<>((item1,item2)->item2.count-item1.count);
  12. for (int i=0;i<s.length();i++){
  13. char c = s.charAt(i);
  14. map.put(c,map.get(c)==null?1:map.get(c)+1);
  15. }
  16. map.forEach((k,v)->{
  17. final Item item = new Item(k, v);
  18. priorityQueue.offer(item);
  19. });
  20. StringBuilder stringBuilder = new StringBuilder();
  21. while(!priorityQueue.isEmpty()){
  22. final Item item = priorityQueue.poll();
  23. for (int i = 0; i < item.count; i++) {
  24. stringBuilder.append(item.character);
  25. }
  26. }
  27. return stringBuilder.toString();
  28. }