题解 | #字符统计#
字符统计
https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0
while(line = await readline()){
const obj={}
for(let i=0;i<line.length;i++){//将出现的字符及次数保存在对象中
if(obj[line[i]])obj[line[i]]++
else obj[line[i]]=1
}
const obj1={}
for(let item in obj){//将次数作为键,字符作为值保存在对象中,好处是可以合并出现相同次数的字符
if(obj1[obj[item]]) obj1[obj[item]].push(item),obj1[obj[item]].sort()//在这里执行出现相同次数的字符的ASC码排序
else obj1[obj[item]]=[],obj1[obj[item]].push(item)
}
const arr=Object.keys(obj1)//将次数添加到数组中
arr.sort((a,b)=>{//对次数进行降序排序
return b-a
})
let res=[]
for(let i=0;i<arr.length;i++){//按照排好的顺序进行数组的合并
res=res.concat(obj1[arr[i]])
}
console.log(res.join(''))
}
