【问题标题】:Recursive JS Function To Move Specific Characters To End Of String将特定字符移动到字符串末尾的递归 JS 函数
【发布时间】:2020-04-11 06:57:51
【问题描述】:

例如:

  1. moveAllXToEnd("xxre") --> "rexx"
  2. moveAllXToEnd("xxhixx") --> "hixxxx"
  3. moveAllXToEnd("xhixhix") --> "hihixxx"
function moveAllXToEnd(str, count = 1) {

    if (str.length <= 1) {
        return str;
    }

    // console.log(str.length, count);
    if (str.length === count) {
        return str;
    }

    if (str[count] === 'x') {
        // Removing the x and putting the '' empty string
        let splicedString = str.substr(0, count) + '' + str.substr(count + 1);
        // Adding back the 'x' to the end of the string
        splicedString += str[count];
        return moveAllXToEnd(splicedString, count + 1);
    }

    return moveAllXToEnd(str, count + 1);
}

【问题讨论】:

    标签: javascript node.js string substring coding-style


    【解决方案1】:

    测试字符串参数的第一个字符是否为x。如果是,则返回与x 连接的递归调用 - 否则,返回与递归调用连接的第一个字符:

    console.log(moveAllXToEnd("xxre")) // --> "rexx"
    console.log(moveAllXToEnd("xxhixx")) // --> "hixxxx"
    console.log(moveAllXToEnd("xhixhix")) // --> "hihixxx"
    function moveAllXToEnd(str) {
      if (str.length <= 1) {
        return str;
      }
      return str[0] === 'x'
        ? moveAllXToEnd(str.slice(1)) + 'x'
        : str[0] + moveAllXToEnd(str.slice(1));
    }

    count 变量看起来没有任何作用。

    【讨论】:

      【解决方案2】:

      尝试将所有非目标字符连接起来,并将所有目标字符附加到末尾:

      function moveAllXToEnd (input) {
          return input.replace(/x+/g, "") + input.replace(/[^x]+/g, "");
      }
      
      console.log(moveAllXToEnd("xxre"));
      console.log(moveAllXToEnd("xxhixx"));
      console.log(moveAllXToEnd("xhixhix"));

      构成output 的第一项只是去掉所有x 的原始输入。为此,我们在最后连接输入中的所有 x。

      【讨论】:

        猜你喜欢
        • 2018-11-05
        • 1970-01-01
        • 2021-10-04
        • 1970-01-01
        • 1970-01-01
        • 2018-02-25
        • 2014-03-06
        • 2013-08-25
        • 2017-04-12
        相关资源
        最近更新 更多