我想编写一个反向数组函数,但遇到了问题。编译器说我的输入和我的输出是相同的。
为什么会这样?
要求:
不要为另一个数组分配额外的空间,必须通过使用O(1)额外的内存就地修改输入数组来实现。
示例1:
输入:
["h","e","l","l","o"]
输出:["o","l","l","e","h"]
示例2:
输入:
["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]
这是我的JS:
var reverseString = function(str) {
var nowArray = [];
nowArray.push(str);
var newArray = [];
for(let i=nowArray.length-1, k=0; i>=0; i--, k++) {
newArray[k] = nowArray[nowArray.length-1];
nowArray.length--;
}
console.log(newArray);
};
reverseString( ["h","e","l","l","o"]) // Should return["o","l","l","e","h"]
答案 0 :(得分:0)
您要将整个字符串而不是单个字符推入nowArray
。相反,只需执行var nowArray = str.split("")
即可获取字符数组。
var reverseString = function(str) {
var nowArray = str.split("");
var newArray = [];
for (let i = nowArray.length - 1, k = 0; i >= 0; i--, k++) {
newArray[k] = nowArray[nowArray.length - 1];
nowArray.length--;
}
console.log(newArray);
};
reverseString("hello");
此外,您正在将字符数组而不是字符串传递给reverseString
函数。
此外,由于将字符串拆分为nowArray
,因此可以消除第二个数组,而仅使用该数组。这也使您可以将迭代次数减半。
var reverseString = function(str) {
var nowArray = str.split("");
for (let i = nowArray.length - 1, k = 0; i > k; i--, k++) {
[nowArray[i], nowArray[k]] = [nowArray[k], nowArray[i]];
}
console.log(nowArray);
};
reverseString("hello");
答案 1 :(得分:0)
您不需要push()
中的str
nowArray
。这将使其变为
[["h","e","l","l","o"]]
您可以直接将其设置为nowArray
var reverseString = function(str){
var nowArray=str;
var newArray=[];
for(let i=nowArray.length-1,k=0;i>=0;i--,k++){
newArray[k]=nowArray[nowArray.length-1];
nowArray.length--;
}
console.log(newArray);
};
reverseString( ["h","e","l","l","o"])//Should return["o","l","l","e","h"]
中使用以下内容
var reverseString = function(s) {
for(let i = 0;i<Math.floor(s.length/2);i++){
let temp = s[i];
s[i] = s[s.length - 1 - i]
s[s.length - 1 - i] = temp;
}
};
答案 2 :(得分:0)
我猜您需要将答案作为数组,因此需要将字符串强制数组化。 您可以使代码更简单:
var reverseString = function(str){
var newStr = [];
for(var i in str) {
newStr.unshift(str[i]);
}
return newStr;
};
答案 3 :(得分:0)
Jacky,您还可以在不占用额外内存的情况下就地修改阵列。这将使用原始字符串并交换两个端点的值。确保在str.length/2
处退出循环,否则将获得完全相同的数组。此外,由于您正在更改原始输入,因此由于js通过引用传递了参数,因此您无需返回任何内容。
var reverseString = function(str){
for(let i = 0; i < str.length/2; i++){
// you can swap like this ES6
[str[i],str[str.length-i-1]] = [str[str.length-i-1],str[i]];
// or like this
//var tmp = str[i];
//str[i] = str[str.length-i-1]];
//str[str.length-i-1]] = tmp;
}
console.log(str);
};
reverseString( ["h","e","l","l","o"])//Should return["o","l","l","e","h"]