题解 | #字符串排序#
字符串排序
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 chars = line.split('');
// 保存所有的字母和索引
let entries = [];
for(let i = 0; i < chars.length; i++){
if(/[a-zA-Z]/.test(chars[i])){
entries.push({index: i, value: chars[i]});
}
}
entries.sort((a, b)=>{
// 大小写相同,根据索引来判断,索引小的在前面(输入顺序)
if(a.value.toLowerCase().codePointAt(0) === b.value.toLowerCase().codePointAt(0)){
return a.index - b.index;
}else{
return a.value.toLowerCase().codePointAt(0) - b.value.toLowerCase().codePointAt(0);
}
});
let j = 0;
// 用排好序的字母替换原数组中的字母
for(let i = 0; i < chars.length; i++){
if(/[a-zA-Z]/.test(chars[i])){
chars[i] = entries[j++].value;
}
}
console.log(chars.join(''));
}
}()

查看1道真题和解析