Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
Array item `String` is not mutable

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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(" ")
};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda