一、题目

给定一个字符串,请将字符串里的字符按照出现的频率降序排列。

点击查看原题
难度级别: 中等

二、思路

1)hashMap+优先队列

使用哈希表记录每个字符出现过多少次
使用优先队列将字符从高频到低频排列,并将其组织成字符串

三、代码

1)hashMap+优先队列

  1. class Solution {
  2. public String frequencySort(String s) {
  3. Map<Character, Integer> map = new HashMap();
  4. for (char c : s.toCharArray()) {
  5. map.put(c, map.getOrDefault(c, 0) + 1);
  6. }
  7. PriorityQueue<Node> pq = new PriorityQueue<Node>((n1, n2)->{
  8. return n2.cnt -n1.cnt;
  9. });
  10. for (Map.Entry<Character, Integer> entry : map.entrySet()) {
  11. pq.offer(new Node(entry.getKey(), entry.getValue()));
  12. }
  13. StringBuilder builder = new StringBuilder();
  14. while (!pq.isEmpty()) {
  15. Node node = pq.poll();
  16. int cnt = node.cnt;
  17. while (cnt-- > 0) {
  18. builder.append(node.c);
  19. }
  20. }
  21. return builder.toString();
  22. }
  23. public class Node {
  24. public char c;
  25. public int cnt;
  26. public Node(char c, int cnt) {
  27. this.c = c;
  28. this.cnt = cnt;
  29. }
  30. }
  31. }

时间复杂度为O(n*logn),空间复杂度为O(n)