palindrome string

Palindrome String

A palindrome string is a string that reads the same forwards and backwards. For example, "racecar" is a palindrome string because it reads the same way both forwards and backwards.

There are several ways to check if a string is a palindrome:

Method 1: Using a loop


function isPalindrome(str) {
  for (let i = 0; i < str.length / 2; i++) {
    if (str[i] !== str[str.length - 1 - i]) {
      return false;
    }
  }
  return true;
}

console.log(isPalindrome("racecar")); // true
console.log(isPalindrome("hello")); // false

This method uses a loop to iterate through the string and check if the characters at the beginning and end of the string are the same. If they are not the same, the function returns false. If the loop completes without returning false, it means the string is a palindrome and the function returns true.

Method 2: Using the reverse method


function isPalindrome(str) {
  const reversedStr = str.split("").reverse().join("");
  return str === reversedStr;
}

console.log(isPalindrome("racecar")); // true
console.log(isPalindrome("hello")); // false

This method uses the reverse method to reverse the string and then compares it to the original string. If they are the same, the function returns true, otherwise it returns false.

Both methods work equally well, but the second method is shorter and more concise. However, it may not be as efficient as the first method since it creates a new string by reversing the original string.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe