题目描述
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.
分析
注意忽略非字母数字的字符
代码
public static boolean isPalindrome(String s) {
if (s.length() <= 1) {
return true;
}
char[] chars = s.toLowerCase().toCharArray();
for (int st = 0, ed = chars.length - 1; st <= ed; st++, ed--) {
while (st < ed && !isValid(s, st))
st++;
while (st < ed && !isValid(s, ed))
ed--;
if (chars[st] != chars[ed])
return false;
}
return true;
}
static boolean isValid(String s, int i) {
char c = s.charAt(i);
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z')|| (c >= 'A' && c <= 'Z');
}