Given a string, determine if it is a palindrome,
considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
input: 可以呼略大小寫跟空白
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function(s) {}
怎麼解
基本上看到回文題目都跟 Two Pointer 有關,我都習慣 pointer 當頭,ind 當 尾這樣 (不過命名你可以隨便命)。
var isPalindrome = function(s) {
let re = /\W*/g;
s = s.toLowerCase().replace(re, '');
let pointer = 0;
let ind = s.length - 1;
while(pointer <= ind){
if(s[pointer] !== s[ind]){
return false;
}else{
pointer ++;
ind --;
}
}
return true;
};