The idea is to use two pointers loop from begin and end respectively, if both are letters, then compare… if not move the pointer until reach letter(s).
Convert to Uppercase before loop, and a separate method to validate a letter.
public class Solution {
public boolean isPalindrome(String s) {
if(s == null){
return false;
}
if(s.length() == 0){
return true;
}
s = s.toUpperCase();
int b = 0;
int e = s.length() - 1;
while(b < e){
if(isAlphaNumeric(s.charAt(b)) && isAlphaNumeric(s.charAt(e))){
if(s.charAt(b) == s.charAt(e)){ //||(char)(s.charAt(b) - 32) == s.charAt(e)||s.charAt(b) == (char)(s.charAt(e) - 32)){
b++;
e--;
}else{
return false;
}
}else{
if(!isAlphaNumeric(s.charAt(b))){
b++;
}
if(!isAlphaNumeric(s.charAt(e))){
e--;
}
}
}
return true;
}
private boolean isAlphaNumeric(char c){
if((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')){
return true;
}
return false;
}
}
没有评论:
发表评论