Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: “A man, a plan, a canal: Panama”
Output: true
Example 2:
Input: “race a car”
Output: false
判断一个字符串是不是有效的回文字符串,忽略字母和数字以外的字符
思路:
双指针,指向头尾,然后向中间移
注意:
(1). 不区分大小写
(2). 中间有连续的非字母数字的字符,需要用while来跳过而不是if
(3). 要判断字母和数字
public boolean isPalindrome(String s) {
if (s == null || s == "") {
return true;
}
int start = 0;
int end = s.length() - 1;
String str = s.toLowerCase();
while(start < end) {
while (start < end && !isAlpha(str.charAt(start))) {
start ++;
}
while (start < end && !isAlpha(str.charAt(end))) {
end --;
}
if(str.charAt(start) != str.charAt(end)) {
return false;
}
start ++;
end --;
}
return true;
}
public boolean isAlpha(char ch) {
if ((ch >= 97 && ch <= 122) || (ch >= '0' && ch <= '9')) {
return true;
}
return false;
}