Problem: A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string s
, return true
if it is a palindrome*, or false
otherwise*.
Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
Example 3:
Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.
There is a lot of solution for this problem I provide two easy ways to solve this problem.
Solution 1: Using regex, trim and reverse.
var isPalindrome = function(s) {
// remove non-alphanumeric characters and uppercase letter.
const str = s.replace(/^a-zA-Z0-9/g, "").toLowerCase();
return str.split("").reverse().join() === str;
}
Solution 2: Using two pointer and regex.
Declare l variable starts from 0 and r variable starts from s.length - 1.
Create a loop and compare s[l] and s[r] if each character is equal return true else return false.
const check = (s) => {
let l = 0;
let r = s.length - 1;
while (l < s) {
if (s[l] === s[r]) {
l++;
r--;
} else {
return false;
}
}
return true;
}
var isPalindrome = function(s) {
const str = s.replace(/^a-zA-Z0-9/g, "").toLowerCase();
return check(str);
}