为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

心有法竹 2022-12-18 16:22:41
如何比我的解决方案更正确地反转初始字符串并节省空间顺序。我需要从初始字符串进行转换,以将其反转但保留与初始字符串相同的空格顺序 '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"
查看完整描述

5 回答

?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

function test(str) {

  const letters = str.split(""); // make array so we can modify it

  const spaceIndexes = letters.reduce((arr, letter, index) => {

    if (letter === " ") arr.push(index);

    return arr;

  }, []);

  const reversed = letters.filter(l => l !== ' ').reverse(); // reverse and delete spaces

  spaceIndexes.forEach((index) => reversed.splice(index, 0, " ")); // insert spaces at previous places

  return reversed.join(""); // return as a string

}


查看完整回答
反对 回复 2022-12-18
?
不负相思意

TA贡献1777条经验 获得超10个赞

您可以在不拆分的情况下进行一个循环,并从末尾获取非空格字符,如果在新字符串的实际长度处找到一个空格,则插入空格。


function test(str) {

    let i = str.length,

        s = '';


    while (i--) {

        if (str[i] === ' ') continue;

        while (str[s.length] === ' ') s += ' ';

        s += str[i];

    }

    return s;

}


console.log(test('some text with spaces'));


查看完整回答
反对 回复 2022-12-18
?
温温酱

TA贡献1752条经验 获得超4个赞

let theString = "some text with spaces";

let spaceArr = []  // we will store spaces position in this array

let pos = 0

let strArr = theString.split(" ")

for(let i=0; i<strArr.length-1; i++){

  spaceArr.push(pos + strArr[i].length)

  pos = pos+1 + strArr[i].length

}

// now lets remove spaces , reverse string, put back orignal spaces 

let res = strArr.join("").split("").reverse().join("").split("")

spaceArr.forEach((item,index)=>{

  res.splice(item,0," ") 

})

console.log(res.join(""))


查看完整回答
反对 回复 2022-12-18
?
qq_笑_17

TA贡献1818条经验 获得超7个赞

不确定是否有比这更好的解决方案。但我现在能想到的最好的

算法

  • 找出indexes给定空间string

  • 反转一样sting

  • 按照添加空间indexes got above并替换任何额外的空间string

function test(str) {

  const mapping = {};

  const pattern = /\s+/g;

  while (match = pattern.exec(str)) {

    mapping[match.index] = true;

  }


  return str.split('').reverse().reduce((acc, cur, index) => {

    if(mapping[index]) acc += ' ';

    acc += cur.replace(pattern, '');

    return acc;

  }, '');

}


// seca psht iwtx etemos

console.log(test('some text with spaces'))


查看完整回答
反对 回复 2022-12-18
?
慕村9548890

TA贡献1884条经验 获得超4个赞

这将以相反的顺序返回所有非空白字母,所有空格都位于原始字符串的位置:


function test(str) {

  let i=-1,spaces=[];

  while ((i=str.indexOf(' ',i+1))>-1) spaces.push(i); // find space positions

  let res=str.replace(/ /g,'').split('').reverse();   // remove spaces and 

                                                      // turn into array and reverse it

  spaces.forEach(i=>res.splice(i,0,' '))              // put spaces back into array

  return res.join('');                                // turn array to string and return

}


let str="let us try this function.";

console.log(str);

console.log(test(str))


查看完整回答
反对 回复 2022-12-18
  • 5 回答
  • 0 关注
  • 183 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号