题解 | #字符串排序#
字符串排序
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 const setMap = (arr, irr, char) => { // 用于记录大小写的顺序 let tempChar; let value; if(/^[A-Z]$/.test(char)){ // 大写用“0”表示 tempChar=char.toLowerCase(); value="0"; } else { // 小写用“1”表示 tempChar=char; value="1"; } arr.push(tempChar); if (irr.has(tempChar)) { let str = irr.get(tempChar); irr.set(tempChar,str.concat(value)); }else irr.set(tempChar,value); }; while ((line = await readline())) { let arr = []; // 保存字母的小写 let irr = new Map(); // 保存原本是大、小写的顺序 let brr = new Map(); // 保存非字母 let str = ""; for (let i = 0; i < line.length; i++) { if (/^[a-zA-Z]$/.test(line[i])) { setMap(arr,irr,line[i]); } else brr.set(i,line[i]); } arr.sort(); let j = 0; // arr[]的index for(let i = 0; i < line.length; i++) { if(brr.has(i))str=str.concat(brr.get(i)); else{ // 根据保存在irr的大小写顺序将字母的大小写形式恢复 let temp=arr[j]; let strLen = irr.get(temp); if(strLen[0]==="0")temp = arr[j].toUpperCase() str=str.concat(temp); irr.set(arr[j],strLen.slice(1)); j++; } } console.log(str); } })();