题解 | #字符串排序#

字符串排序

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())) {
        const tokens = `${line}`.split("");
		// 先过滤不需要排序的字符串
        const sortCodes = tokens.filter((t, inx) => {
            return /[a-z]/gi.test(t);
        });
		// 再对数组进行排序,大小写忽视
        sortCodes.sort((a, b) => {
            const aCode = `${a}`.toLocaleLowerCase().charCodeAt(0);
            const bCode = `${b}`.toLocaleLowerCase().charCodeAt(0);
            return aCode - bCode;
        });
        let inx = 0;
		// 根据原来的字符串遍历,如果是排序自负则去排序数组取出来
		// 注意inx是取出的顺序
        const res = tokens.map(t => {
            if (/[a-z]/gi.test(t)) {
                const v = sortCodes[inx];
                inx ++;
                return v;
            } else {
                return t;
            }
        })
        console.log(res.join(""));
    }
})();

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务