[LeetCode] 451. Sort Characters By Frequency
Posted aaronliu1991
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 451. Sort Characters By Frequency相关的知识,希望对你有一定的参考价值。
根据字符出现频率排序。题意是给一个字符串,请按照出现字符的频率高低重新排列这个字符并输出。例子,
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.
注意此题的第三个例子,要求区分大小写。思路是用到类似桶排序bucket sort的思路,用一个hashmap记录input里面所有出现过的字符和他们的频率,然后对hashmap(key, value)按照value大小对key重新排序。最后再按照各个字母出现的次数,拼接好最后的字符串。
时间O(nlogn) - need to sort the hashmap
空间O(n) - hashmap
1 var frequencySort = function(s) { 2 let map = {}; 3 //get hash map of letter count 4 for (let letter of s) { 5 // map[letter] = (map[letter] || 0) + 1; 6 if (map[letter]) { 7 map[letter]++; 8 } else { 9 map[letter] = 1; 10 } 11 } 12 let res = ‘‘; 13 // sort the letter by count 14 let sorted = Object.keys(map).sort((a, b) => map[b] - map[a]); 15 16 // generate result from the sorted letter 17 for (let letter of sorted) { 18 for (let count = 0; count < map[letter]; count++) { 19 res += letter; 20 } 21 } 22 return res; 23 };
以上是关于[LeetCode] 451. Sort Characters By Frequency的主要内容,如果未能解决你的问题,请参考以下文章
[leetcode-451-Sort Characters By Frequency]
[LeetCode] 451. Sort Characters By Frequency
Leetcode 451. Sort Characters By Frequency JAVA语言
451. Sort Characters By Frequency