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.
This is an easy problem that can be solved as ususal palindrome, but the trick here is to judge whether a character is a letter or not.
So here we use Character.isLetterOrDigit()
function in Java.
Notice that some other solutions used regexp, to replace all the other characters into “”, this is quite slow, tho.
class Solution {
public boolean isPalindrome(String s) {
s=s.trim();
s=s.toLowerCase();
if(s.length()==0) return true;
int low=0, high=s.length()-1;
while(low<=high){
char clow = s.charAt(low), chigh = s.charAt(high);
if(!Character.isLetterOrDigit(clow)) {low++;continue;}
if(!Character.isLetterOrDigit(chigh)) {high--;continue;}
if(clow!=chigh) return false;
high--;low++;
}
return true;
}
}