题解 | #字符串排序#

字符串排序

https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584

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

void (async function () {
    // Write your code here
    while ((line = await readline())) {
        //抽取字母,排序
        let regex = /[a-zA-Z]/gi;
        let orderedChars = line
            .match(regex)
            .sort(
                (a, b) =>
                    a.toUpperCase().charCodeAt() - b.toUpperCase().charCodeAt()
            );

        //替换,拼接
        let result = [];
        let index = 0;
        for (let i = 0; i < line.length; i++) {
            if (/[a-zA-Z]/.test(line.charAt(i))) {
                result.push(orderedChars[index]);
                index++;
            } else {
                result.push(line.charAt(i));
            }
        }
        console.log(result.join(""));
    }
})();

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务