Home > Back-end >  Palindrome checker does not function properly with "almostomla"
Palindrome checker does not function properly with "almostomla"

Time:06-16

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"?

CodePudding user response:

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"));

CodePudding user response:

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;
}
  • Related