华为机试题45题,名字的漂亮度。
const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); const ipt = []; rl.on("line", (line) => { ipt.push(line.split(' ')); }).on('close', () => { fun45(ipt); }); const fun45 = (ipt) => { const helper = (str) => { // 定义 helper 函数,其返回值为某一字符串的漂亮值,注意本题所有字符都是小写字母 let arr = new Array(26).fill(0), res = 0; // arr 长度为 26,用来存储每个字母对应的个数,下标 0 对应小写字母 a for (let i = 0; i < str.length; i++) { arr[str.charCodeAt(i) - 97]++; // 将每个字母出现的个数记录下来 } arr = arr.filter(e => e > 0).sort((a, b) => b - a); // 将 arr 中非零的数保存下来并将其降序排列 for (let i = 0; i < arr.length; i++) { // 计算漂亮值,个数最多的字符的漂亮值为26,依此类推 res += (26 - i) * arr[i]; } return res; }; let n = Number(ipt.shift()[0]); // 取出 n 值 for (let i = 0; i < n; i++) { console.log(helper(ipt[i][0])); // 依次输出每个字符串的漂亮值 } }