Home > Software design >  Break out of a while loop to find a Palindrome
Break out of a while loop to find a Palindrome

Time:08-07

This code does not work!

It causes the browser to crash;

Can someone please help me debug this? Not sure what is wrong.

My assumption is I have a pointer at the beginning of the string and the end of the string, And I check if each character is the same, and finish once the end and beginning pointer get to the middle...

But like I said it's not working.

function isPalindrome(string) {
  let isStringPalindrome = true;
  let left = 0;
  let right = string.length - 1;

  let middle = Math.floor((left   right)/2);

  while(string[left] === string[right]){
    left   1;
    right - 1;
    if (left === middle && right === middle) {
      break;  
    }
    if (string[left] !== string[right]) {
      isStringPalindrome = false;
      break; 
    }
  }
    return isStringPalindrome;
}

CodePudding user response:

Well, the two pointers idea is a good way to check palindrome. But in your code, you don't update the value of left and right. And if the string has even characters, the condition left === middle && right === middle will never be true.

We can slightly change your code:

function isPalindrome(string) {
  let left = 0;
  let right = string.length - 1;

  while(left < right){
    if (string[left] !== string[right]) {
      return false;
    }
    left  = 1;
    right -= 1;
  }
  
  return true;
}

console.log(isPalindrome("abba"));
console.log(isPalindrome("aba"));
console.log(isPalindrome("abc"));
console.log(isPalindrome("a"));

CodePudding user response:

  1. 'left' and 'right' variable is not updating inside the loop.
  2. Logic is little bit off inside the loop. The String with the length of even number never break out of the loop and that's why the browser is crashing.

I changed your function a bit.

function isPalindrome(string) {
    let isStringPalindrome = true;
    let left = 0;
    let right = string.length - 1;
    if (string.length == 0) return false
    while(left <= right){
      if (string[left] !== string[right]) {
        isStringPalindrome = false;
        break; 
      }
      left = left   1;
      right = right - 1;
    }
      return isStringPalindrome;
  }

There are tons of articles available to solve palindrome in different ways.

  • Related