LeetCode 451. Sort Characters By Frequency (根据字符出现频率排序)

Given a string, sort it in decreasing order based on the frequency of characters.

Example 1:

Input:
"tree"

Output:
"eert"

Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.

 

Example 2:

Input:
"cccaaa"

Output:
"cccaaa"

Explanation:
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.

 

Example 3:

Input:
"Aabb"

Output:
"bbAa"

Explanation:
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.

 

 


 题目标签:Hash Table | Heap

  题目给了我们一个string s, 让我们把s 按照每一个char 的出现频率从大到小排序。

  首先遍历string s,把每一个char 当作 key, 出现次数当作 value 存入 map;

  接着利用priorityQueue,按照 value 从大到小的 顺序 排列,把map 的data 存入 pq;

  遍历 pq,把每一个char 按照 它的value 组成对应长度 string 存入 res。

 

 

Java Solution:

Runtime beats 40.06% 

完成日期:06/23/2017

关键词:HashMap; Priority Queue

关键点:把Map 存入 pq

 1 class Solution 
 2 {
 3     public String frequencySort(String s) 
 4     {
 5         HashMap<Character, Integer> map = new HashMap<>();
 6         StringBuilder res = new StringBuilder();
 7         
 8         // store s char and frequency into map
 9         for(char c: s.toCharArray())
10             map.put(c, map.getOrDefault(c, 0) + 1);
11         
12         // set up priorityQueue in value descending order
13         PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>(
14             new Comparator<Map.Entry<Character, Integer>>()
15             {
16                 public int compare(Map.Entry<Character, Integer> a, Map.Entry<Character, Integer> b)
17                 {
18                     return b.getValue() - a.getValue();
19                 }
20             }
21         );
22         
23         // add map into priorityQueue
24         pq.addAll(map.entrySet());
25         
26         // iterate pg, add each char with value times into res 
27         while(!pq.isEmpty())
28         {
29             Map.Entry<Character, Integer> entry = pq.poll();
30             
31             for(int i=0; i<(int) entry.getValue(); i++)
32                 res.append(entry.getKey());
33         }
34         
35         return res.toString();
36     }
37 }

参考资料:

https://discuss.leetcode.com/topic/66024/java-o-n-bucket-sort-solution-o-nlogn-priorityqueue-solution-easy-to-understand

 

LeetCode 题目列表 - LeetCode Questions List

posted @ 2017-11-10 06:12  Jimmy_Cheng  阅读(401)  评论(0编辑  收藏  举报