5ms Java Solution with comments


  • 0
    V

    You can use Character class operations as well to convert to lower case and to check for alphnumeric or you can write on your own checking their ascii values

    public class Solution {
        public boolean isAlpha(char c){
            //check if its alphabets or numeric 
            if(c >=65 && c<=90)return true;
            if(c>=97 && c<= 122)return true;
            if(c>=48 && c<=57) return true;
            return false;
        }
        public boolean isPalindrome(String s) {
            if(s == null) return true;
            if(s.length() == 0 || s.length() == 1) return true;
            int  start = 0, end = s.length()-1;
            char c,d;
            
            while(start<=end){
                c = s.charAt(start);
                d = s.charAt(end);
                //till you get alphanumeric on left side
                while( (start<end) &&  !isAlpha(c)){ start++;c = s.charAt(start); }
                //till you get alphanumeric on right side
                while( (start<end) && !isAlpha(d)){end --;d = s.charAt(end); }
                
                //if u have still managed to get non-alphanumeric, then this guy is either middle element or alone,so palindrome
                if(!isAlpha(c) || !isAlpha(d))return true;
                
                //change to lowercase
                if(c<91) c += 32;
                if(d<91) d += 32;
                //now compare for palindrome.
                if(c != d)return false;
                
                start++;
                end--;
            }
            return true;
        }
    }

Log in to reply
 

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