451. Sort Characters By Frequency

Posted gopanama

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了451. Sort Characters By Frequency相关的知识,希望对你有一定的参考价值。

 

 

 1 //用list比较快
 2 class Solution {
 3     public String frequencySort(String s) {
 4         if(s.length() == 0 || s.length() == 1) return s;
 5         HashMap<Character, Integer> map = new HashMap<>();
 6         char[] arr = s.toCharArray();
 7         for(int i = 0; i < arr.length; i++) {
 8             map.put(arr[i], map.getOrDefault(arr[i], 0)+1);
 9         }
10         List<Character>[] arr2 = new List[s.length()+1];
11         for(char c : map.keySet()) {
12             if(arr2[map.get(c)] == null) {
13                 List<Character> list = new ArrayList<>();
14                 list.add(c);
15                 arr2[map.get(c)] = list;
16             }else {
17                 arr2[map.get(c)].add(c);
18             }
19         }
20         
21         
22         StringBuilder sb = new StringBuilder();
23         for(int i = arr2.length-1; i > 0; i--) {
24             if(arr2[i] != null) {
25                 for(int j = 0; j < arr2[i].size(); j++) {
26                     for(int k = 0; k < i; k++) {
27                         
28                     sb.append(arr2[i].get(j));
29                     }
30                 }
31                 
32             }
33                 
34         }
35         return sb.toString();
36         
37     }
38 }
39 
40 
41 
42 //too slow
43 class Solution {
44     public String frequencySort(String s) {
45         if(s.length() == 0 || s.length() == 1) return s;
46         HashMap<Character, Integer> map = new HashMap<>();
47         char[] arr = s.toCharArray();
48         for(int i = 0; i < arr.length; i++) {
49             map.put(arr[i], map.getOrDefault(arr[i], 0)+1);
50         }
51         HashMap<Integer, List<Character>> map2 = new HashMap<>();
52         for(char c : map.keySet()) {
53             if(map2.containsKey(map.get(c))) {
54                 map2.get(map.get(c)).add(c);
55             }else {
56                 List<Character> list = new ArrayList<>();
57                 list.add(c);
58                 map2.put(map.get(c), list);
59                 
60             }    
61         }
62         StringBuilder sb = new StringBuilder();
63         List<Integer> list = new ArrayList<>(map2.keySet());
64         Collections.sort(list);
65         for(int i : list) {
66             for(int j = 0; j < map2.get(i).size(); j++) {
67                 for(int k = 0; k < i; k++) {
68                     sb.insert(0, map2.get(i).get(j));
69                 }
70             }
71         }
72         return sb.toString();
73         
74     }
75 }

 

以上是关于451. Sort Characters By Frequency的主要内容,如果未能解决你的问题,请参考以下文章

451. Sort Characters By Frequency

451. Sort Characters By Frequency

451. Sort Characters By Frequency

451. Sort Characters By Frequency

leetcode 451. Sort Characters By Frequency

[leetcode-451-Sort Characters By Frequency]