码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 451. Sort Characters By Frequency

时间:2020-01-23 13:58:02      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:思路   桶排序   +=   sam   字符   pre   hash   rom   sorted   

根据字符出现频率排序。题意是给一个字符串,请按照出现字符的频率高低重新排列这个字符并输出。例子,

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

标签:思路   桶排序   +=   sam   字符   pre   hash   rom   sorted   

原文地址:https://www.cnblogs.com/aaronliu1991/p/12230497.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!