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.
分析:做这个题目的关键是理清题目的思路,看清判断一个字符串是否是回文的,忽略字符的大小写,并且值关注字母与数字,无视其他字符如标点符号。Step1:把字符串先转化为小写;
Step2:分别有两个下标i和j,分别向后和向前移动得到当前的字符c1和c2,如果有字符不是数字或小写字母,则无视这个继续移动一步。
Step3:继续循环的条件是i>j;
/**
* 判断一个字符串是否是回文的,忽略字符的大小写,并且值关注字母与数字,无视其他字符如标点符号。
* Step1:把字符串先转化为小写;
* Step2:分别有两个下标i和j,分别向后和向前移动得到当前的字符c1和c2,如果有字符不是数字或小写字母,则无视这个继续移动一步。
* Step3:继续循环的条件是i>j;
*/
public boolean isPalindrome(String s) {
s = s.toLowerCase();
char sArr[] = s.toCharArray();
int len = sArr.length;
if(len<=0){
return true;
}else{
int i = 0;
int j = len-1;
while(i<=j){
char c1 = sArr[i];
char c2 = sArr[j];
/*找到当前符合条件的需要比较的c1,注意数字作为char型时需要加上48*/
while(!(c1>='a' && c1<='z' || c1>=0+48 && c1<=9+48) && i<j){
i++;
c1 = sArr[i];
}
/*找到当前符合条件的需要比较的c2*/
while(!(c2>='a' && c2<='z' || c2>=0+48 && c2<=9+48) && i<j){
j--;
c2 = sArr[j];
}
if(c1 != c2){
return false;
}
i++;
j--;
}
}
return true;
}
701

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



