Description

451. 根据字符出现频率排序
难度中等181
给定一个字符串,请将字符串里的字符按照出现的频率降序排列。
示例 1:
输入:

  1. "tree"

输出:

  1. "eert"

解释:
‘e’出现两次,’r’和’t’都只出现一次。
因此’e’必须出现在’r’和’t’之前。此外,”eetr”也是一个有效的答案。

示例 2:
输入:

  1. "cccaaa"

输出:

  1. "cccaaa"

解释:
‘c’和’a’都出现三次。此外,”aaaccc”也是有效的答案。
注意”cacaca”是不正确的,因为相同的字母必须放在一起。

示例 3:
输入:

  1. "Aabb"

输出:

  1. "bbAa"

解释:
此外,”bbaA”也是一个有效的答案,但”Aabb”是不正确的。
注意’A’和’a’被认为是两种不同的字符。

Solution

使用 HashMap 统计字符出现的频率,再根据 字符的频率进行排序和拼接结果

  1. class Solution {
  2. public String frequencySort(String s) {
  3. HashMap<Character, Integer> map = new HashMap<Character, Integer>();
  4. for(int i = 0; i < s.length(); i ++){
  5. char key = s.charAt(i);
  6. if(map.containsKey(key)){
  7. map.put(key,map.get(key)+1);
  8. }else
  9. map.put(key,1);
  10. }
  11. StringBuilder res = new StringBuilder();
  12. List<Character> list = new LinkedList<>();
  13. for( Character key : map.keySet() ) // 将 hashmap 中的 key 存到 list 中
  14. list.add(key);
  15. // 遍历 list,每轮遍历中找到当前 list 中,频率最大的那个元素,相同元素则比较 ASCII 码的大小
  16. while (list.size() > 0){
  17. Character max = list.get(0);
  18. for (int i = 1; i < list.size(); i ++){
  19. Character temp = list.get(i);
  20. if (map.get(max) < map.get(temp))
  21. max = temp;
  22. else if (map.get(max) == map.get(temp) && (max.compareTo(temp) < 0) )
  23. max = temp;
  24. }
  25. // 拼接到 res
  26. int count = map.get(max);
  27. while ( count > 0 ) {
  28. res.append(max);
  29. count --;
  30. }
  31. // 在 list 中移除这个元素
  32. list.remove(max);
  33. }
  34. return res.toString();
  35. }
  36. }