描述
编写一个程序,将输入字符串中的字符按如下规则排序。
规则 1 :英文字母从 A 到 Z 排列,不区分大小写。
如,输入: Type 输出: epTy
规则 2 :同一个英文字母的大小写同时存在时,按照输入顺序排列。
如,输入: BabA 输出: aABb
规则 3 :非英文字母的其它字符保持原来的位置。
如,输入: By?e 输出: Be?y
数据范围:输入的字符串长度满足 1 \le n \le 1000 \1≤n≤1000
输入描述:
输入字符串
输出描述:
输出字符串
代码
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function fn(str){
let arr = str.split('') || []
let copyArr = arr.slice(0) || []
let reg = /[a-zA-Z]/
let onlyLetter = []
let otherCharIndex = {}
let resArr = []
for(let i = 0; i < copyArr.length; i++){
if(reg.test(copyArr[i])){
onlyLetter.push(copyArr[i])
}else{
otherCharIndex[i] = i
}
}
let letterSorted = onlyLetter.sort((i, j) => {
let a = i.toLowerCase();
let b = j.toLowerCase();
return a.charCodeAt() - b.charCodeAt();
})
for(let i = 0; i < copyArr.length; i++){
if(otherCharIndex[i] != null){
resArr.push(copyArr[i])
}else{
resArr.push(letterSorted.shift())
}
}
return resArr.join('')
}
rl.on('line', function (line) {
console.log(fn(line))
});