Find if a string is palindrome using javascript

Checks if the given string is a palindrome using javascript

@author: Abhijit Padhy 
@github: https://github.com/abhijit-padhy


const checkIsGivenStringAPalindrome = (str) => {

const stringLength = str.length;
const mid = Math.floor(stringLength/2);
let isPalindrome = true;
let less = 1, more = 1;

// For even number of letters the logic will be slightly different
if (stringLength % 2 === 0) {
more = 0;
}

for (let i = mid; i > 0; i--) {
if (str[mid - less] !== str[mid + more]) {
isPalindrome = false;
}
less = less + 1;
more = more + 1;
}
return isPalindrome;
};

checkIsGivenStringAPalindrome('madam');
// true


checkIsGivenStringAPalindrome('iadaj');
// false


checkIsGivenStringAPalindrome('paap');
// true

Keywords: javascript, palindrome, coding, programming, java, interview, c, c++, node js

Comments

Popular posts from this blog

Abhijit Padhy

Find the longest substring in a given string.

Find the robot matching the given query having [top, right, bottom, left] index of the nearest walls in a 2D array.