功能保持超时

这就是问题:


完成函数 splitPairs,将输入字符串拆分为字符对。如果输入字符串的长度为奇数,则应将最后一对中缺失的第二个字符替换为下划线 _。请注意,一个空字符串应该使您的函数产生一个空数组。


这是我的代码(它一直超时):


function splitPairs(input) {

  let inputArray = input.split('');

  let result = [];

      

  if (inputArray.length % 2 !== 0) {

    for (let i = 0; i < inputArray.length; i + 2) {

      let pair = inputArray[i] + inputArray[i+1];

      //push that onto the result array

      result.push(pair);

    }

    result.push(inputArray[inputArray.length - 1] + '_');      

  } else {

    for (let i = 0; i < inputArray.length; i + 2) {

      let pair = inputArray[i] + inputArray[i+1];

      result.push(pair);

    }

  }

  return result;

}

我做错了什么,解决这个问题的正确方法是什么?如果我可以自己编写解决方案会更好但是我可以使用帮助来了解我应该使用什么方法来解决它


达令说
浏览 124回答 4
4回答

梦里花落0921

超时是因为您没有递增i。i + 2计算新值但不将其分配到任何地方。你可以i通过做i += 2which 的简写来更新i = i + 2。

白衣非少年

您需要使用i+=2. 此外,解决方案中存在一些错误:function splitPairs(input) {&nbsp; let inputArray = input.split('');&nbsp; let result = [];&nbsp; if(!inputArray)&nbsp; &nbsp; return result;&nbsp; if (inputArray.length % 2 !== 0) {&nbsp; &nbsp; for (let i = 0; i < inputArray.length-1; i+=2) {&nbsp; &nbsp; &nbsp; let pair = inputArray[i] + inputArray[i+1];&nbsp; &nbsp; &nbsp; result.push(pair);&nbsp; &nbsp; }&nbsp; &nbsp; result.push(inputArray[inputArray.length - 1] + '_');&nbsp; &nbsp;&nbsp;&nbsp; } else {&nbsp; &nbsp; for (let i = 0; i < inputArray.length; i += 2) {&nbsp; &nbsp; &nbsp; let pair = inputArray[i] + inputArray[i+1];&nbsp; &nbsp; &nbsp; result.push(pair);&nbsp; &nbsp; }&nbsp; }&nbsp; return result;}console.log(splitPairs(""));console.log(splitPairs("abcd"));console.log(splitPairs("abcde"));评论中提到的一个更简单的解决方案(一个循环)是:function splitPairs(input) {&nbsp; let inputArray = input.split('');&nbsp; let result = [];&nbsp; if(!inputArray)&nbsp; &nbsp; return result;&nbsp; let odd = (inputArray.length % 2 !== 0);&nbsp; let len = (odd) ? inputArray.length-1 : inputArray.length;&nbsp; for (let i = 0; i < len; i+=2) {&nbsp; &nbsp; let pair = inputArray[i] + inputArray[i+1];&nbsp; &nbsp; result.push(pair);&nbsp; }&nbsp; if(odd)&nbsp; &nbsp; result.push(inputArray[inputArray.length - 1] + '_');&nbsp; &nbsp;&nbsp;&nbsp; return result;}console.log(splitPairs(""));console.log(splitPairs("abcd"));console.log(splitPairs("abcde"));

至尊宝的传说

您可以使用一个(两个)衬垫var&nbsp;result=str.split(/(..)/).filter(v=>v) if&nbsp;(result[result.length-1].length==1)&nbsp;result[result.length-1]+="_"

德玛西亚99

你可以这样做function splitPairs(input) {&nbsp; return input.split('').map((c, i) => {&nbsp; &nbsp; if (i % 2 !== 0) return;&nbsp; &nbsp; if (input[i+1]) {&nbsp; &nbsp; &nbsp; return input[i] + input[i+1];&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; return input[i] + '_';&nbsp; }).filter(pair => pair);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript