forked from JoshCrozier/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0451-sort-characters-by-frequency.js
50 lines (41 loc) · 1.27 KB
/
0451-sort-characters-by-frequency.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* 451. Sort Characters By Frequency
* https://leetcode.com/problems/sort-characters-by-frequency/
* Difficulty: Medium
*
* Given a string, sort it in decreasing order
* based on the frequency of characters.
*/
/**
* @param {string} s
* @return {string}
*/
var frequencySort = function(s) {
const map = new Map();
s.split('').forEach(char => {
map.set(char, map.has(char) ? map.get(char) + 1 : 1);
});
return [...map]
.sort((a, b) => b[1] - a[1])
.map(entry => entry[0].repeat(entry[1]))
.join('');
};
// Doesno work with big string Why?
// var frequencySort = function(s) {
// const freqMap = new Map();
// // Подсчёт частоты символов
// for (const ch of s) {
// freqMap.set(ch, (freqMap.get(ch) || 0) + 1);
// }
// const maxHeap = new MaxHeapAdhoc();
// // Заполняем макс-хипу (отрицательное значение для симуляции макс-хипы)
// for (const [ch, freq] of freqMap.entries()) {
// maxHeap.add([-freq, ch.repeat(freq)]);
// }
// let result = "";
// // Извлекаем символы в порядке убывания частоты
// while (maxHeap.heap.length) {
// result += maxHeap.poll()[1];
// }
// return result;
// };