题解 | #字符串排序#
字符串排序
http://www.nowcoder.com/practice/5190a1db6f4f4ddb92fd9c365c944584
思路:1、把所有“文本”全部那出来并排序好 2、再把文本按照输入的顺序一个个放上去,其他符号不变化
const sortInputArr = input.split('');
const sortObj = {} // 排序后的对象
sortInputArr.forEach((item, index) => {
if (/[A-Z]/.test(item)) {
sortObj[item.charCodeAt(0) + 32]
? sortObj[item.charCodeAt(0) + 32].push(item)
: sortObj[item.charCodeAt(0) + 32] = [item];
} else if (/[a-z]/.test(item)) {
sortObj[item.charCodeAt(0)]
? sortObj[item.charCodeAt(0)].push(item)
: sortObj[item.charCodeAt(0)] = [item]
}
})
// 纯字母文本
const charSortInput = Object.values(sortObj).join('').match(/[a-zA-Z]/g);
let resStr = '';
input.split('').forEach(item => {
// 如果是其他字符
if(/[^a-zA-Z]/.test(item)) {
resStr += item;
} else {
charSortInput[0] && (resStr += charSortInput[0]);
charSortInput.shift();
}
})
print(resStr)