如何反转初始字符串并节省空间顺序

如何比我的解决方案更正确地反转初始字符串并节省空间顺序。我需要从初始字符串进行转换,以将其反转但保留与初始字符串相同的空格顺序 'some text with spaces' //=> "seca psht iwtx etemos"


function test(str, result = "") {

  let res = str.split('').reverse().join('')


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

    if (str[i] === " ") {

      result += ` ${res[i]}`

      str[i + 1];

    } else if (str[i] !== " " && res[i] === " ") {

      result += ""

    } else {

      result += res[i];

    }

  }

  return result

}


console.log(test('some text with spaces')) //=> "seca psht iwtx etemos"


心有法竹
浏览 184回答 5
5回答

慕田峪7331174

function test(str) {&nbsp; const letters = str.split(""); // make array so we can modify it&nbsp; const spaceIndexes = letters.reduce((arr, letter, index) => {&nbsp; &nbsp; if (letter === " ") arr.push(index);&nbsp; &nbsp; return arr;&nbsp; }, []);&nbsp; const reversed = letters.filter(l => l !== ' ').reverse(); // reverse and delete spaces&nbsp; spaceIndexes.forEach((index) => reversed.splice(index, 0, " ")); // insert spaces at previous places&nbsp; return reversed.join(""); // return as a string}

不负相思意

您可以在不拆分的情况下进行一个循环,并从末尾获取非空格字符,如果在新字符串的实际长度处找到一个空格,则插入空格。function test(str) {&nbsp; &nbsp; let i = str.length,&nbsp; &nbsp; &nbsp; &nbsp; s = '';&nbsp; &nbsp; while (i--) {&nbsp; &nbsp; &nbsp; &nbsp; if (str[i] === ' ') continue;&nbsp; &nbsp; &nbsp; &nbsp; while (str[s.length] === ' ') s += ' ';&nbsp; &nbsp; &nbsp; &nbsp; s += str[i];&nbsp; &nbsp; }&nbsp; &nbsp; return s;}console.log(test('some text with spaces'));

温温酱

let theString = "some text with spaces";let spaceArr = []&nbsp; // we will store spaces position in this arraylet pos = 0let strArr = theString.split(" ")for(let i=0; i<strArr.length-1; i++){&nbsp; spaceArr.push(pos + strArr[i].length)&nbsp; pos = pos+1 + strArr[i].length}// now lets remove spaces , reverse string, put back orignal spaces&nbsp;let res = strArr.join("").split("").reverse().join("").split("")spaceArr.forEach((item,index)=>{&nbsp; res.splice(item,0," ")&nbsp;})console.log(res.join(""))

qq_笑_17

不确定是否有比这更好的解决方案。但我现在能想到的最好的该算法是找出indexes给定空间string反转一样sting按照添加空间indexes got above并替换任何额外的空间stringfunction test(str) {&nbsp; const mapping = {};&nbsp; const pattern = /\s+/g;&nbsp; while (match = pattern.exec(str)) {&nbsp; &nbsp; mapping[match.index] = true;&nbsp; }&nbsp; return str.split('').reverse().reduce((acc, cur, index) => {&nbsp; &nbsp; if(mapping[index]) acc += ' ';&nbsp; &nbsp; acc += cur.replace(pattern, '');&nbsp; &nbsp; return acc;&nbsp; }, '');}// seca psht iwtx etemosconsole.log(test('some text with spaces'))

慕村9548890

这将以相反的顺序返回所有非空白字母,所有空格都位于原始字符串的位置:function test(str) {&nbsp; let i=-1,spaces=[];&nbsp; while ((i=str.indexOf(' ',i+1))>-1) spaces.push(i); // find space positions&nbsp; let res=str.replace(/ /g,'').split('').reverse();&nbsp; &nbsp;// remove spaces and&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // turn into array and reverse it&nbsp; spaces.forEach(i=>res.splice(i,0,' '))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // put spaces back into array&nbsp; return res.join('');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // turn array to string and return}let str="let us try this function.";console.log(str);console.log(test(str))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript