题解 | #字符串排序#
字符串排序
http://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
const input = readline().split('');
const helper = [];
const letter = /[A-Z]/i;
// 保存非字母的字符和其所在下标
const nonLetter = new Map();
// 把字母按插入排序的思路做由小到大排序
// 把非字母的字符及其位置下标单独保存起来,当所有字母排序完成后,在按原先下标位置插回去
for (let i = 0, len = input.length; i < len; i++) {
const cur = input[i];
// 是字母
if (letter.test(cur)) {
let j = helper.length;
for (; j > 0; j--) {
if (helper[j - 1].toLowerCase() > input[i].toLowerCase()) {
helper[j] = helper[j - 1];
continue;
}
break;
}
helper[j] = input[i];
} else {
nonLetter.set(i, cur);
}
}
for (const [i, v] of nonLetter.entries()) {
helper.splice(i, 0, v);
}
console.log(helper.join(''));
查看7道真题和解析