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

437
Visualizações
Palindrome checker does not function properly with "almostomla"

function palindrome(str) {
  const forward = str.replace(/[^a-zA-Z ]/g, "").toUpperCase()
  const reversed = str.replace(/[^a-zA-Z ]/g, "").toUpperCase()
  for (let i = 0; i < forward.length; i++) {
    for (let k = reversed.length - 1; k >= 0; k--) {
      if (forward[i] === reversed[k]) {
        return true
      } else {
        return false
      }
    }
  }
}

console.log(palindrome("almostomla"));

Why is this not working?? does my loop just creates a new "s"?

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

0

You don't need nested loops, that will compare every character with every other character. You just want to compare the first character with the last character, 2nd character with 2nd-to-last character, and so on. So there should just be a single loop that increments i and decrements k in lock step.

You shouldn't return true when you find a match, because there could be later characters that don't match. Return false when you find a mismatch, and return true if you make it through the loop without returning.

You don't need both forward and reversed variables, since they're the same. Just convert the input string to uppercase once, and use that for both.

You don't need to iterate through the whole string, you can stop when you get to the middle.

function palindrome(str) {
  const upper = str.replace(/[^a-zA-Z ]/g, "").toUpperCase()
  for (let i = 0, k = upper.length - 1; i < upper.length/2; i++, k--) {
    if (upper[i] !== upper[k]) {
      return false
    }
  }
  return true;
}

console.log(palindrome("almostomla"));
console.log(palindrome("almotomla"));
console.log(palindrome("almottomla"));

about 4 years ago · Juan Pablo Isaza Relatório

0

You might want this:

function palindrome(str) {
  const forward = str.replace(/[^a-zA-Z ]/g, "").toUpperCase()
  var n = forward.length
  for (let i = 0; i < n; i++) {
      if (forward[i] !== forward[n-i-1]) {
        return false;
      }
  }
  return true;
}
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