Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Notice
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.
Example
"A man, a plan, a canal: Panama"
is a palindrome.
"race a car"
is not a palindrome.
注意:在使用正则表达式的时候需要使用replaceAll方法
public class Solution {
/*
* @param s: A string
* @return: Whether the string is a valid palindrome
*/
public boolean isPalindrome(String s) {
// write your code here
if (s == null || s.length() == 0) {
return true;
}
s = s.toLowerCase().trim().replaceAll("[^a-z0-9]", "");
int left = 0, right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
}