在不使用内置函数且没有附加数组的情况下反转句子

时间:2019-03-17 12:40:28

标签: javascript

这个问题在这里已经问过几次了,但是我在这里看不到完全解决的答案。我本人已尝试过此方法,但几乎无法解决,但无法完全解决问题。我的代码对我来说似乎很好,但是只能反转句子中的第一个单词。我做错了什么? 输入是“完美的练习”预期的输出是“完美的练习”,但我得到了“练习sekam tcefrep”

var inputarray=['p','e','r','f','e','c','t',' ','m','a','k','e','s',' ','p','r','a','c','t','i','c','e'];

var len = inputarray.length;

// reverse sentence
function reverse(start, end){
    for(var i=start; i<end/2; i++){ 
        var temp = inputarray[len-1-i];
        inputarray[len-1-i] =  inputarray[i] ;
        inputarray[i] = temp;
    }
}

//reverse words characters
function reverse2(starts, ends, lens){
    for(var i=starts; i<ends/2; i++){ 
        var temp = inputarray[lens-1-i];
        inputarray[lens-1-i] =  inputarray[i] ;
        inputarray[i] = temp;
    }
}

//reverse all chars
reverse(0,len);

var start=0;
var last=0;
for(var j=0; j<len; j++){
    if(inputarray[j]==" " || j==len-1){
        last=j;
        console.log(`reversing from ${start} to ${last}`);
        reverse2(start,last, last-start);
        start=last;
    }
}


console.log(inputarray);

3 个答案:

答案 0 :(得分:0)

你去了:)

const input = [
    "p",
    "e",
    "r",
    "f",
    "e",
    "c",
    "t",
    " ",
    "m",
    "a",
    "k",
    "e",
    "s",
    " ",
    "p",
    "r",
    "a",
    "c",
    "t",
    "i",
    "c",
    "e"
];

let output = [];
let word = [];

for (let i = input.length - 1; i > -1; i--) {
    const char = input[i];
    if (char !== " ") {
        word.unshift(char);
    } else {
        output = [...output, ...word, " "];
        word = [];
    }

    if (i === 0) {
        output = [...output, ...word];
    }
}

console.log(output);

答案 1 :(得分:0)

使用splice

的另一种选择

var inputarray=['p','e','r','f','e','c','t',' ','m','a','k','e','s',' ','p','r','a','c','t','i','c','e'];
var result = [];
for(var x=0, y=0; x<inputarray.length; x++, y++) {
	if (inputarray[x]==' ') {
		// reset index counter & append space on first index
		y=-1; result.splice(0,0,' ');
	} else {
		// append word
		result.splice(y,0,inputarray[x]);
	}
}
console.log(result)

答案 2 :(得分:0)

在这里,不使用内置函数或其他数组:

var inputArray=['p','e','r','f','e','c','t',' ','m','a','k','e','s',' ','p','r','a','c','t','i','c','e'];

function reverse(array, start = 0, end = array.length) {
  for (let i = start, j = end - 1; i < j; i++, j--) {
    const temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
}

function reverseWords(array, delim = ' ') {
  reverse(array);

  let start = 0;
  for (let i = 0; i < array.length; i++) {
    if (array[i] == delim) {
      reverse(array, start, i);
      start = i + 1;
    }
  }
  reverse(array, start, array.length);

  return array;
}

console.log(reverseWords(inputArray));