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.
参杂噪音的回文判断
public class Solution {
public boolean isPalindrome(String s) {
if (s.trim().length() == 0) {
return true;
}
char[] parts = s.trim().toLowerCase().toCharArray();
int low = 0;
int high = parts.length - 1;
while (low < high) {
while (low < parts.length && !isLetter(parts[low])) {
low++;
}
while (high >= 0 && !isLetter(parts[high])) {
high--;
}
if (low >= high) {
return true;
} else if (parts[low] != parts[high]) {
return false;
} else {
low++;
high--;
}
}
return true;
}
public boolean isLetter(char input) {
return (input >= 'a' && input <= 'z') || (input >= 'A' && input <= 'Z')
|| (input >= '0' && input <= '9');
}
}