题解 | #字符串排序#
字符串排序
https://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
计数排序和js内置sort排序两种实现方式
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
// 方法一:计数排序
void (async function () {
let list = (await readline()).split("");
let arr = Array.from(new Array(26), () => []);
for (const item of list) {
const code = item.toLowerCase().charCodeAt();
if (code >= 97 && code <= 122) arr[code - 97].push(item);
}
arr = arr.reduce((pre, cur) => [...pre, ...cur]);
let index = 0;
for (let i = 0; i < list.length; i++) {
const code = list[i].toLowerCase().charCodeAt();
if (code >= 97 && code <= 122) list[i] = arr[index++];
}
console.log(list.join(""));
})();
// 方法二:sort排序,arr.sort((a,b) => a.toLowerCase().charCodeAt() - b.toLowerCase().charCodeAt());
void (async function () {
let list = (await readline()).split("");
let arr = []
for (const item of list) {
if((item >= "a" && item <= "z")||(item >= "A" && item <= "Z")) arr.push(item);
}
arr.sort((a,b) => a.toLowerCase().charCodeAt() - b.toLowerCase().charCodeAt());
let index = 0;
for (let i = 0; i < list.length; i++) {
const code = list[i].toLowerCase().charCodeAt();
if (code >= 97 && code <= 122) list[i] = arr[index++];
}
console.log(list.join(""));
})();


查看5道真题和解析