换个思路
提高了速度,但是也增加了代码量,分享一个思路吧。
还可以吧通用的获取字母码点的值提取出来
代码
const stringSort = (str) => {
const arr = new Array(62).fill(0);
for (let i = 0; i < str.length; i++) {
const e = str[i];
if (/\d/.test(e)) {
arr[Number(e)] += 1;
} else if (/[A-Z]/.test(e)) {
arr[10 + e.codePointAt() - 'A'.codePointAt()] += 1;
} else {
arr[36 + e.codePointAt() - 'a'.codePointAt()] += 1;
}
}
return arr.reduce((init, cur, idx) => {
return init + getCharsFromIdx(idx, cur);
}, '');
};
const getCharsFromIdx = (idx, repeat) => {
if (idx < 10) {
return String(idx).repeat(repeat);
} else if (idx < 36) {
return String.fromCodePoint(idx - 10 + 'A'.codePointAt()).repeat(repeat);
} else {
return String.fromCodePoint(idx - 36 + 'a'.codePointAt()).repeat(repeat);
}
};
while(input = readline()) {
console.log(stringSort(input))
}