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.
题意:判断一个字符串是否是回文,字符串中非数字和字母的字符可忽略,空字符串是回文串。
思路:
用两个游标分别指向首尾。
首尾游标各自向中间移动,碰到非数字和字母的跳过,否则停在遇到的字母或数字索引位置处。
比较首尾游标所指字符是否相同。
注意:移动游标时,要判断游标是否越界;比较两个字符时需要都转为大写或小写。自己在这两个地方出现了bug。
public boolean isPalindrome(String s) {
if (s == null || s.length() < 2) {
return true;
}
for (int left = 0, right = s.length() - 1; left < right; left++, right--) {
while (!Character.isLetterOrDigit(s.charAt(left))) {
left++;
}
while (!Character.isLetterOrDigit(s.charAt(right))) {
right--;
}
if (left < right && s.charAt(left) != s.charAt(right)) {
return false;
}
}
return true;
}