问题描述
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
解决思路
首先记得将字母转成小写。然后所有设置两个指针begin和end,分别从头和从尾移动,如果不是字母就跳过,如果是就判断首尾是否相同。
问题解惑
这道题不能忽视数字包含的情况,因为一开始,我使用的是Character.isLetter()
,但这个不能处理包含数字的情况,所以要改用Character.isLetterOrDigit
。
代码
package leetcode;
public class ValidPalindrome {
public boolean isPalindrome(String s) {
if (s == null || s.length() == 0){
return true;
}
int begin = 0;
int end = s.length() - 1;
s = s.toLowerCase();
while (begin < end){
if (!Character.isLetterOrDigit(s.charAt(begin))){
begin++;
continue;
}
if(!Character.isLetterOrDigit(s.charAt(end))){
end--;
continue;
}
if (s.charAt(begin) == s.charAt(end)){
begin++;
end--;
}else {
return false;
}
}
return true;
}
}