字符串排序

字符串排序

https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584?tpId=37&tqId=21249&rp=1&ru=/ta/huawei/&qru=/ta/huawei&difficulty=3&judgeStatus=&tags=/question-ranking

参考一楼的想法,自己码了一遍,也加了点注释,个别处做了点小改变。


const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on('line', function (line) {
    let result = line.split('')
    //先收集英文字母,对其进行排序
    let words = line.match(/[a-z]+/ig).join('').split('')
    words.sort(function(a,b){
        a = a.toLowerCase();
        b = b.toLowerCase();//规则1 不区分大小写
        return a<b?-1:0 //升序排列(因为前面全都转化成小写,故不会改变同一字母大小写的相对顺序)
    })
    result.forEach((item,index)=>{//将words中字母替换result中的字母,非英文字符不替换
        if(/[a-z]/i.test(item)){//是英文字符,则替换
            result[index] = words[0];
            words.shift();
        }
    })
    console.log(result.join(''))
});
全部评论

相关推荐

09-29 16:18
门头沟学院 Java
点赞 评论 收藏
分享
6 收藏 评论
分享
牛客网
牛客企业服务