Valid Palindrome
Strip the string down to lowercase alphanumerics, then check the cleaned string against its reverse.
The problem
A phrase is a palindrome if, after converting every uppercase letter to lowercase and removing all non-alphanumeric characters, it reads the same forwards and backwards.
Given a string `s`, return whether it's a palindrome. An empty string after cleaning counts as one, since it reads the same either way.
The approach
My idea is to first form a string with nothing but the alphanumeric characters, lowercasing as I go. A small `isAlphanumeric` helper tests each character with a regex, and I append the ones that pass to `final_string`.
Then it's a plain palindrome check: a `reverseString` helper splits, reverses, and re-joins the cleaned string, and I return whether `final_string` equals its reverse.
The solution
/**
* @param {string} s
* @return {boolean}
*/
const isAlphanumeric = (input) => /^[a-z0-9]+$/gi.test(input)
const reverseString = (input) => input.split("").reverse().join("")
var isPalindrome = function(s) {
let final_string = ""
for (el of s) {
if (isAlphanumeric(el)) {
final_string += String(el).toLowerCase()
}
}
return final_string == reverseString(final_string)
};Time O(n)Space O(n)