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
Comments
Post a Comment