LeetCode - 125. Valid Palindrome
Thoughts:
I choose two pointer to solve this problem, when I need to compare two values.
The time complexity is O(n) for the iteration.
Thoughts visuzlization:
s = "A man, a plan, a canal: Panama"
first, make all the characters lowercase
second, split the string into an array
third, transform characters into ascii code and filter the non-alphanumeric characters
fourth, join the array back into a string
then compare the two values by two pointer
"amanaplanacanalpanama"
l r
"amanaplanacanalpanama"
l r
"amanaplanacanalpanama"
l r
... and so on
if there is a mismatch, return false
and just return true in the end
Code:
/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function (s) {
const filtered = s
.toLowerCase()
.split('')
.filter((char) => {
const ascii = char.charCodeAt(0);
const isNumber = ascii >= 48 && ascii <= 57;
const isAlphabet = ascii >= 97 && ascii <= 122;
return isNumber || isAlphabet;
})
.join('');
let l = 0;
let r = filtered.length - 1;
while (l < r) {
if (filtered[l] !== filtered[r]) {
return false;
}
l++;
r--;
}
return true;
};
Reference
Copyright © 2024 | All rights reserved.