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.
分析:
判断字符串是否回文思路比较清楚,维护首位两个游标逐字符比较即可。
这个题有几个其他要求:
1,只考虑数字和字母,其他字符不考虑
2,不区分字母的大小写,即认为"A"=="a"
这实际上是判断之前对字符串进行一些预处理,应该想到正则表达式在这里可能有用武之地,把非字母数字全部删去,并将大小写统一即可。
public class Solution {
public boolean isPalindrome(String s) {
if(s == null) return false;
//将非字母和数字的字符替换为空,即删去
s = s.replaceAll("[^a-z0-9A-Z]","");
if(s.length() == 0) return true;
s = s.toLowerCase();
int i = 0;
int j = s.length()-1;
while(i < j){
if(s.charAt(i) != s.charAt(j))
return false;
i++;
j--;
}
return true;
}
}