关键点:判断当前字符是不是字母或数字
class Solution {
public boolean isPalindrome(String s) {
if(s== null || s.length()<2) return true;
String sl= s.toLowerCase();
int start= 0, end= s.length()-1;
while(start<end){
while(start<end && (sl.charAt(start)<'0' || (sl.charAt(start)>'9' && sl.charAt(start)<'a') || sl.charAt(start)>'z')){
start++;
}
while(start<end &&(sl.charAt(end)<'0' || (sl.charAt(end)>'9' && sl.charAt(end)<'a') || sl.charAt(end)>'z')){
end--;
}
if(sl.charAt(start)!= sl.charAt(end)){return false;}
start++;end--;
}
return true;
}
}
看到的一种很快的判断方式
class Solution {
private static final int[] map = new int[256];
static{
for(int i = 0; i < 10; i++){
map[i + '0'] = (i + 1);
}
for(int i = 0; i < 26; i++){
map[i + 'a'] = map[i + 'A'] = (i + 11);
}
}
public boolean isPalindrome(String s) {
char[] arrays = s.toCharArray();
int start = 0, end = arrays.length - 1;
int startVal, endVal;
while(start < end){
startVal = map[arrays[start]];
endVal = map[arrays[end]];
if(startVal != 0 && endVal != 0){
if(startVal != endVal)
return false;
start++;
end--;
}else{
if(startVal == 0) start++;
else end--;
}
}
return true;
}
}