題目:
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
AC:
public boolean isPalindrome(String s) {
if (s == null || s.length() < 2) {
return true;
}
int left = 0;
int right = s.length() - 1;
char[] chars = s.toLowerCase().toCharArray();
while (left < right) {
while (left < right && !isValidChar(chars[left])) {
left++;
}
while (left < right && !isValidChar(chars[right])) {
right--;
}
if (chars[left] == chars[right]) {
left++;
right--;
} else {
return false;
}
}
return true;
}
private boolean isValidChar(char ch) {
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9')) {
return true;
}
return false;
}
當然也可以用Character來判斷是否合法。