Home > Net >  Array item is not mutable
Array item is not mutable

Time:07-13

I'm trying to solve 557 on leetCode with two pointers, and I found a strange behavior, which I cannot explain.

Below is my code

/**
 * @param {string} s
 * @return {string}
 */
var reverseWords = function(s) {
    // return s.split(" ").map(w => w.split("").reverse().join("")).join(" ")
    let arr = s.split(" "), w
    for(let i = 0; i < arr.length; i  ){
        let x = arr[i], left = 0, right = x.length - 1, holder = null
        while(left < right){
            holder = x[left]
            x[left] = x[right]
            x[right] = holder
            left  = 1
            right -= 1
        }
    }
    return arr.join(" ")
};

and example "Let's take LeetCode contest"

while I can move the while loop to a function and solve it in a different way, I'm not sure why x is not changing, from my understanding this is an array item and can be changed.

CodePudding user response:

This happens because the variable "x" is not an array but a String which comes from the variable "arr" to make it work you need to change

let x = arr[i]

to

let x = arr[i].split("")

the correct code is:

var reverseWords = function(s) {
    // return s.split(" ").map(w => w.split("").reverse().join("")).join(" ")
    let arr = s.split(" "), w
    for(let i = 0; i < arr.length; i  ){
        let x = arr[i].split(""), left = 0, right = x.length - 1, holder = null
        while(left < right){
            holder = x[right]
            x[right] = x[left]
            x[left] = holder
            left  = 1
            right -= 1
        }
        arr[i] = x.join("");
    }
    return arr.join(" ")
};
  • Related