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
题目
判断回文串,只检查字母,不分大小写。
思路
双指针
代码
class Solution {
public boolean isPalindrome(String s) {
s = s.toLowerCase();
int left = 0;
int right = s.length()-1;
while(left < right){
// check white spaces
if(!Character.isLetterOrDigit(s.charAt(left))) left++;
// check white spaces
else if(!Character.isLetterOrDigit(s.charAt(right))) right--;
else if(s.charAt(left) != (s.charAt(right))) return false;
else {
left++ ;
right--;
}
}
return true;
}
}