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 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
题目比较简单,注意别把数字排除。判断是否相等是记得统一大小写,有个非常好用的方法 Character.toLowerCase(char)
public class Solution {
public boolean isPalindrome(String s) {
if (s == null) {
return false;
}
if (s.length() < 1) {
return true;
}
int i = 0;
int j = s.length() - 1;
while (i < j) {
char left = s.charAt(i);
char right = s.charAt(j);
if (!((left >= 'a' && left <= 'z') || (left >= 'A' && left <='Z') || (left >= '0' && left <='9'))) {
i++;
continue;
}
if (!((right >= 'a' && right <= 'z') || (right >= 'A' && right <='Z') || (right >= '0' && right <='9'))) {
j--;
continue;
}
if (Character.toLowerCase(left) != Character.toLowerCase(right)) {
return false;
}
i++;
j--;
}
return true;
}
}