原题:(频率5)
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.
题意:判断是否是合格的回文串,忽略空格和标点符号
代码和思路:
class Solution {
public boolean isPalindrome(String s) {
if(s.isEmpty()) return true;
//双指针法
int start = 0;
int end = s.length()-1;
while(start<=end){
char cstart = s.charAt(start);
char cend = s.charAt(end);
//首位向中间走,如果不是字母或数字,跳过
if(!Character.isLetterOrDigit(cstart)) start++;
else if(!Character.isLetterOrDigit(cend)) end--;
//是数字或字母的话,判断是否相等,相等的话继续向中间移动
else{
if(Character.toLowerCase(cstart)!=Character.toLowerCase(cend)) return false;
start++;
end--;
}
}
return true;
}
}
本文介绍了一种使用双指针法判断字符串是否为回文的方法,该方法忽略了所有非字母数字字符,并对大小写不敏感。适用于空字符串的情况。
1861

被折叠的 条评论
为什么被折叠?



