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.
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.
Solution:
The solution is simple. Two pointers, one from left to right, the other one from right to left. Only consider alphabetic characters and ignore all other characters. Return false once we find the unmatched chars. Otherwise, move two pointers towards each other till they meet.
Time complexity: O(n)
Time complexity: O(n)
public boolean isPalindrome(String s) {
if(s==null) return false;
int l=0;
int r=s.length()-1;
while(l<r){
if(!isValidChar(s.charAt(l))){
l++;
continue;
}
if(!isValidChar(s.charAt(r))){
r--;
continue;
}
if(Character.toLowerCase(s.charAt(l))!=Character.toLowerCase(s.charAt(r))) return false;
l++;
r--;
}
return true;
}
public boolean isValidChar(char c){
return (c<='z'&& c>='a') || (c<='Z' && c>='A') || (c<='9' && c>='0');
}
No comments:
Post a Comment