125. Valid Palindrome
time: O(n) ⇒ lowercase
space: O(1)
/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function (str) {
str = str.toLowerCase(); // n
str = str.replace(/[^a-z0-9]/g, ''); // n
console.log(str);
let s = 0;
let e = str.length - 1;
while (s <= e) {
if (str[s] !== str[e]) {
return false;
}
s++;
e--;
}
return true;
};
var isPalindrome = function (str) {
str = str.toLowerCase(); // n
let s = 0;
let e = str.length - 1;
while (s <= e) {
if (!isAlphabetNumber(str[s])) {
s++;
continue;
} else if (!isAlphabetNumber(str[e])) {
e--;
continue;
} else {
if (str[s] !== str[e]) {
return false;
}
s++;
e--;
}
}
return true;
};
function isAlphabetNumber(c) {
if ('0' <= c && c <= '9' ||
'a'.charCodeAt() <= c.charCodeAt() && c.charCodeAt() <= 'z'.charCodeAt()) {
return true;
}
return false;
}
Last updated