My solution in Java within 8ms. Any better solution?


  • 1
    S
    public class Solution {
    public boolean isPalindrome(String s) {
        if(s == null){
            return false;
        }
        if(s.length() <= 1){
            return true;
        }
        int low = 0;
        int high = s.length()-1;
        while(low<high){
            if(shouldIgnore(s.charAt(low))){
                low++;
                continue;
            }
            if(shouldIgnore(s.charAt(high))){
                high--;
                continue;
            }
            if(!isSameLetter(s.charAt(low), s.charAt(high))){
                return false;
            }
            low++;
            high--;
        }
        return true;
    }
    
    public boolean isLetter(char x){
        if(x>=65 && x<=90){
            return true;
        }
        if(x>=97 && x<=122){
            return true;
        }
        return false;
    }
    
    public boolean isSameLetter(char x, char y){
        if(isLetter(x) && isLetter(y)){
            if(x == y || x == y+32 || x+32 == y){
                return true;
            }
        }else{
            if(x == y){
                return true;
            }
        }
        return false;
    }
    
    public boolean shouldIgnore(char x){
        if(x >= 48 && x <= 57){
            return false;
        }
        return !isLetter(x);
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.