题解 | #名字的漂亮度#

名字的漂亮度

https://www.nowcoder.com/practice/02cb8d3597cf416d9f6ae1b9ddc4fde3

第一次做的时候用了map来保证排序后字母和它的数量保持一一对应。然而这道题并不需要知道字母和数量的对应关系,只需要计算漂亮度即可。所以可以用数组来计数,直接排序

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void async function () {
    const n = parseInt(await readline())
    for(let i = 0; i < n; i++) {
        let str = await readline()
        let map = new Array(26).fill(0)
        let res = 0

        // 记录每个字母的数量
        for(let c of str) {
            map[c.charCodeAt(0) - 97]++
        }
        // 降序排列
        map.sort((a,b) => b- a)
        
        // 不需要知道字母数量和哪个字母对应,我们只需要计算漂亮度即可
        let i = 26
        for(let num of map) {
            res += num * i
            i--
        }
        console.log(res)
    }
   
}()

全部评论

相关推荐

03-25 19:00
东北大学 Java
程序员牛肉:太好了,是聊天记录。不得不信了。 当个乐子看就好,不要散播焦虑
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务