簡體   English   中英

如何反轉初始字符串並節省空間順序

[英]How to reverse initial string and save space order

如何比我的解決方案更正確地反轉初始字符串並節省空間順序。 我需要從初始字符串進行轉換,以將其反轉但保持與初始字符串相同的空格順序 '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"

您可以在不拆分的情況下進行一個循環,並從末尾獲取非空格字符,如果在新字符串的實際長度處找到一個空格,則插入空格。

 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'));

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 }

這將以相反的順序返回所有非空白字母,所有空格都位於原始字符串的位置:

 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))

不確定是否有比這更好的解決方案。 但我現在能想到的最好的

算法

  • 找出給定string中的空間indexes
  • 扭轉同樣的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'))

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(""))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM