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:
Basic implementation question.
Solution:
Basic implementation question.
public class Solution {
public boolean isPalindrome(String s) {
// empty string
if(s.length() == 0)
return true;
int l = 0;
int r = s.length() - 1;
while(l < r){
// bypass non-alphanumeric characters
while(!isChar(s.charAt(l)) && l < r) l++;
while(!isChar(s.charAt(r)) && l < r) r--;
// case: Aa and aa, 00, ...
char x = s.charAt(l);
char y = s.charAt(r);
if(Math.abs(x - y) != 32 && Math.abs(x - y) != 0)
return false;
l++;
r--;
}
return true;
}
public boolean isChar(char c){
return (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9');
}
}
No comments:
Post a Comment