Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
思路:
这道题是验证是否是会问字符串,但是字符串中加入了空格和非字母数字的字符,增加了难度。只需要建立两个指针,l和r分别从头和尾开始遍历整个字符串,遇到非数字字母的字符就跳过,继续往下找。等左右指针都找到字符时就比较这两个字符是否相等,不想等返回false,若相等接着比较下面两个找到的字符。在最开始将字母全部转换成小写的。
var isPalindrome = function(s) {
if(! s.length) return true;
s=s.toLowerCase()
var l=0;
var r=s.length-1;
while(l<r){
if(!isAlphaNum(s[l]))l++;
else if(!isAlphaNum(s[r]))r--;
else if(s[l]!=s[r]) return false;
else{
l++;
r--;
}
}
return true;
function isAlphaNum(ch){
if(ch>='a' && ch<='z') return true;
if(ch>='A' && ch<='Z') return true;
if(ch>='0' && ch<='9') return true;
return false;
}
};