451. 根据字符出现频率排序

 1/**
2 * @param {string} s
3 * @return {string}
4 */

5var frequencySort = function(s) {
6    const record = {};
7    const sArr = [...s];
8    sArr.forEach(value => {
9        record[value] = (record[value] || 0) + 1;
10    });
11
12    // a 出现的次数大于 b
13    return sArr.sort((a, b) => record[a] === record[b] ?
14        a.charCodeAt(0) - b.charCodeAt(0) : record[b] - record[a]
15    ).join('');
16};
17
18ensureEqual(frequencySort("tree"), "eert"'test 1');
19ensureEqual(frequencySort("trreee"), "eeerrt"'test 2');
20ensureEqual(frequencySort("abaccadeeefaafcc"), "aaaaacccceeeffbd"'test 3');
21ensureEqual(frequencySort("loveleetcode"), "eeeelloocdtv"'test 4');
posted @ 2018-12-18 16:03  rencoo  阅读(215)  评论(0编辑  收藏  举报