Skip to content
本页目录

字符串问号排序

题目

给定一个字符串,其中仅包含,大小写字母,数字和问号。要求对该字符串内部字符排序,满足以下要求:

  1. 问号的占用的位置不变
  2. 数字占用的位置不变,数字之间由大到小排序
  3. 字母占用的位置不变,字母之间按字典序排序

具体请配合样例理解

样例

输入:

12A?zc

输出:

21A?cz

输入:

1Ad?z?t24

输出:

4Ad?t?z21

输入:

???123??zxy?

输出:

???321??xyz?

代码实现

javascript
function solution(inp) {
  // Edit your code here
  const cArr = []
  const dataArr = []
  for(let c of inp){
    if(c<='9'&&c>='0'){
      cArr.push(c)
    }
    if(c>='A'&&c<='z'){
      dataArr.push(c)
    }
  }
  cArr.sort((a,b)=>b-a)
  dataArr.sort()
  const input = inp.split('')
  for(let i=0;i<input.length;i++){
    const c = input[i]
    if(c<='9'&&c>='0'){
      input[i] = cArr.shift()
    }
    if(c>='A'&&c<='z'){
      input[i] = dataArr.shift()
    }
  }


  return input.join('');
}

function main() {
  // Add your test cases here
  console.log(solution("12A?zc") === "21A?cz");
  console.log(solution("1Ad?z?t24") === "4Ad?t?z21");
  console.log(solution("???123??zxy?") === "???321??xyz?");
}

main();
字符串问号排序 has loaded