24%
Accepted
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Have you met this question in a real interview?
Yes
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.
Challenge
O(n) time without extra memory.
/**
* @param s A string
* @return Whether the string is a valid palindrome
*/
public boolean isPalindrome(String s) {
// Write your code here
if(s == null || s.length() == 0) return true;
s = s.toLowerCase();
int i = 0, j = s.length() - 1;
while(i < j){
if(!Character.isLetterOrDigit(s.charAt(i))) i++;
else if(!Character.isLetterOrDigit(s.charAt(j))) j--;
else if(s.charAt(i) != s.charAt(j)) return false;
else{
i++;
j--;
}
}
return true;
}
}
No comments:
Post a Comment