Solution 1. Just parse string into character array. Then, use another loop to compare the character with head to middle and tail to middle.
var isPalindrome = function(s) {
// parse string into valid character array
let tmp = [];
s.split("").forEach(c=>{
c = c.toLowerCase();
if (c>="a" && c<="z") {
tmp.push(c);
} else if (c>="0" && c<="9") {
tmp.push(c);
}
});
// compare characters from head to middle and tail to middle
let len = tmp.length;
let [i,j] = [0,len-1];
while (i < j) {
if (tmp[i]!==tmp[j]) {
return false;
}
i++;
j--;
}
return true;
};
Solution 2. Optimize it. Only one while loop with one head index and the other tail index. That's the way to stand out.
var isPalindrome = function(s) {
function getChar(c) {
let ret = "";
c = c.toLowerCase();
if (
(c >= "0" && c <= "9") ||
(c >= "a" && c <= "z")
) {
return c;
}
return ret;
}
let len =s.length;
let [headIdx, tailIdx] = [0, len-1];
let headChar="";
let tailChar="";
while (headIdx < tailIdx) {
//a character from head, return blank charater if not valid
if (headChar.length===0) {
headChar = getChar(s[headIdx]);
}
//a character from tail
if (tailChar.length===0) {
tailChar = getChar(s[tailIdx]);
}
//check if both head chacter and tail character valid
//then check they are equal
if (
headChar.length===1 &&
tailChar.length===1
) {
if (headChar===tailChar) {
headChar = "";
tailChar = "";
headIdx++;
tailIdx--;
} else {
return false;
}
} else {
// if not a valid character, move to next index
if (headChar.length===0) {
headIdx++;
}
if (tailChar.length===0) {
tailIdx--;
}
}
}
return true;
};
No comments:
Post a Comment