LeetCode 451. Sort Characters By Frequency (根据字符出现频率排序)
2017-11-10 06:12
639 查看
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
class Solution { public String frequencySort(String s) { HashMap<Character, Integer> map = new HashMap<>(); StringBuilder res = new StringBuilder(); // store s char and frequency into map for(char c: s.toCharArray()) map.put(c, map.getOrDefault(c, 0) + 1); // set up priorityQueue in value descending order PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>( new Comparator<Map.Entry<Character, Integer>>() { public int compare(Map.Entry<Character, Integer> a, Map.Entry<Character, Integer> b) { return b.getValue() - a.getValue(); } } ); // add map into priorityQueue pq.addAll(map.entrySet()); // iterate pg, add each char with value times into res while(!pq.isEmpty()) { Map.Entry<Character, Integer> entry = pq.poll(); for(int i=0; i<(int) entry.getValue(); i++) res.append(entry.getKey()); } return res.toString(); } }
参考资料:
https://discuss.leetcode.com/topic/66024/java-o-n-bucket-sort-solution-o-nlogn-priorityqueue-solution-easy-to-understand
LeetCode 题目列表 - LeetCode Questions List
相关文章推荐
- [LeetCode] Sort Characters By Frequency 根据字符出现频率排序
- [LeetCode] 451. Sort Characters By Frequency 根据字符出现频率排序
- 赫夫曼树(一),对字符串中的字符出现频率进行设置权,并且根据权大小进行排序
- Leetcode451. 对字符出现频率进行排序
- Leetcode 451. Sort Characters By Frequency 按频率对字符排序
- Leetcode 451. Sort Characters By Frequency 按频率对字符排序 解题报告
- 根据数组中数字出现频率排序
- 针对一个文件 统计其中的单词和字符数 找出文件中出现次数最多的单词数 将文件中出现的单词按频率进行排序并输出
- 按字符出现频率对字符进行排序
- 在给定字符串里查找出现频率最高的字符
- 去哪儿笔试题:寻找字符串数组中指定字符出现的字符串并排序
- c语言:计算输入字符各个字母出现的频率思路
- 根据输入的textField首字符排序
- 判断字符串中字符出现的频率
- 在一个字符串中找到出现指定次数的字符,根据用户输入次数,打印出现次数为该次数的字符。如输入abaccedff及1,则输出:b e d 如输入abaccedff及2,则输出:a c f
- 将数组中的字符按出现次数多少排序输出
- Linq EF 根据字符列表排序或List根据列表排序以及Linq查询类型转换
- 将一段(英文)按照字符出现的频率进行倒序排列
- python 排序,根据字符长度,数字,字母
- 单词出现频率降序排序!