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

270
Visualizações
557. Reverse Words in a String III javascript (spacing issue)

I'm solving a problem (leetcode 557) Given a string s, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"

Example 2:

Input: s = "God Ding"
Output: "doG gniD"

When I write the solution below this way I get a wrong answer which is not reversed.

var reverseWords = function(s) {
    let separate = s.split("");
    let res = separate.map((str) => {
        return str.split("").reverse().join("");
    });

    return res.join("")
};

But when I write as shown below my answer is accepted

var reverseWords = function(s) {
    let separate = s.split(" ");
    let res = separate.map((str) => {
        return str.split("").reverse().join("");
    });

    return res.join(" ")
};

I am really confused about how the spacing in quotation marks of the second and last line of code is affecting the solution. Thanks in advance

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

0

s.split("") will find every occurrence of an emtpy string, which is literally between every pair of consecutive characters. So it splits the original string into individual characters. The documentation on mdn has a specific mention of this case:

If separator is an empty string (""), str is converted to an array of each of its UTF-16 "characters".

s.split(" ") will find every occurrence of a space, which has much fewer occurrences of course, and it will split your original string into words.

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