24 March 2024
Easy
125. Valid Palindrome
Link: https://leetcode.com/problems/valid-palindrome
Description: Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Solution:
We need to remove all non-alphanumeric characters and convert the string to lowercase. Then we can use two pointers one at the start and one at the end of the string. We compare the characters at both pointers and move them towards each other. If they are not equal, we return false. If we reach the middle of the string, we return true.
/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function (s) {
const formatted = s.replace(/[^a-zA-Z0-9]/g, '').toLowerCase()
let start = 0
let end = formatted.length - 1
while (start < end) {
if (formatted[start] !== formatted[end]) {
return false
}
start += 1
end -= 1
}
return true
}