Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note that empty string is regarded as a palindrome.
public boolean isPalindrome(String s) {
if (s == null || s.length() == 0)
return true;
s = s.toLowerCase(); // Converted to lowercase for processing convenience
int n = s.length();
int left = 0, right = n-1;
while(left < right) {
// Ignore non-alphanumeric characters
if (!Character.isAlphabetic(s.charAt(left)) && !Character.isDigit(s.charAt(left))) {
left++;
continue;
}
if (!Character.isAlphabetic(s.charAt(right)) && !Character.isDigit(s.charAt(right))) {
right--;
continue;
}
if (s.charAt(left) != s.charAt(right)) // Against the palindrome rule
return false;
left++;
right--;
}
return true;
}
Read full article from LeetCode - Valid Palindrome | Darren's Blog