Question
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.


本题难度Easy。

双指针法

【复杂度】
时间 O(N) 空间 O(1)

【思路】
字串中有字母、数字和其他字符,我们利用两个指针从两端向中间靠拢,碰到字母或数字就停下然后对比两端字符是否相等,否则跳过。这里要先对字串中的大小写字母进行转换。

【代码】

public class Solution {
public boolean isPalindrome(String s) {
//require
if(s==null)return true;
s=s.toLowerCase();//大小写转换
int l=0,r=s.length()-1;
//invariant
while(l<r){
if(!Character.isLetterOrDigit(s.charAt(l))){
l++;
continue;
}
if(!Character.isLetterOrDigit(s.charAt(r))){
r--;
continue;
}
if(s.charAt(l)!=s.charAt(r))
return false;
l++;r--;
}
//ensure
return true;
}
}