题解 | #字符统计#

字符统计

https://www.nowcoder.com/practice/c1f9561de1e240099bdb904765da9ad0

// 文里有两种方法,一种是利用sort方法两次排序。另外一种是自己手动排序


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

function getIndex(val, arr) {
    let inx = -1;
    arr.forEach((item, index) => {
       item.val == val && (inx = index);
    })
    return inx;
}
function getIndex2(val, arr) {
    let inx = -1;
    arr.forEach((item, index) => {
       item.num == val && (inx = index);
    })
    return inx;
}
void async function () {
    // Write your code here
    while(line = await readline()){
        let tokens = line.split('');
        // let a = parseInt(tokens[0]);
        // let b = parseInt(tokens[1]);
        // console.log(a + b);
        let vals = [];
        tokens.forEach((item, index)=> {
            if(tokens.indexOf(item) == index) {
                vals.push({val: item, num: 1});
            } else {
                vals[getIndex(item, vals)].num++;
            }
        })
        // 得到vals [{val: 'a', num: 1}, {val: 'h', num: 3}]
        // 字符升序
        vals.sort((a,b) => {
            if(a.val < b.val) return -1;
            if(a.val > b.val) return 1;
            // return a.val.chartCodeAt() - b.val.chartAt();
        })
        // 次数降序
        vals.sort((a,b) => {
            // if(b.num == a.num) { return b.val - a.val } else {

             return b.num - a.num;
            // }
             });
        // console.log(vals);
        let res = [];
        vals.forEach(item => {
            res.push(item.val);
        })
        console.log(res.join(''));
        // 获取以num为key的数组
        // let arr = [];
        // vals.forEach((item, index)=> {
        //     if(getIndex2(item.num, arr) == -1) {
        //         arr.push({num: item.num, vals: [item.val]});
        //     } else {
        //         let i = getIndex2(item.num, arr);
        //         arr[i].vals.push(item.val);
        //         arr[i].vals.sort();
        //     }
        // })
        // // console.log(arr)
        // let res = [];
        // arr.forEach(item => {
        //     res = res.concat(item.vals)
        // })
        // console.log(res.join(''))
    }
}()

华为机试题 文章被收录于专栏

华为机试题

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务