先用map存储key-count,然后再对count倒序排序再拼接
var frequencySort = function(s) {
let obj = buildTargetObject(s);
const arr = getTargetSort(obj);
return buildStr(arr)
};
function buildTargetObject(str) {
const obj = {}
for(let i = 0; i < str.length; i ++) {
let cur = str[i];
obj[cur] = (obj[cur] || 0) + 1
}
return obj
}
function getTargetSort(obj) {
const arr = Object.entries(obj)
return arr.sort((a, b) => b[1] - a[1])
}
function buildStr(arr) {
let str = '';
for(let i = 0; i < arr.length; i ++) {
let [key, value] = arr[i]
str += key.repeat(value)
}
return str
}
时间复杂度
空间复杂度