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:
- 'left' and 'right' variable is not updating inside the loop.
- 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.