Share my solution, just a while loop, very self-explanatory


  • 2
    L
    public class Solution {
        public boolean isAlphanumeric(char c){
            return (c>='0' && c<='9') || (c>='A' && c<='Z') || (c>='a' && c<='z');
        }
        public char lowCase(char c){
            if((c>='A' && c<='Z')) c =(char) (c + 32);
            return c;
        }
        public boolean isPalindrome(String s) {
            if(s==null) return true;
            int head = 0;
            int tail = s.length()-1;
            
            while(head<tail){
                if(!isAlphanumeric(s.charAt(head))) head ++;
                if(!isAlphanumeric(s.charAt(tail))) tail --;
                if(isAlphanumeric(s.charAt(head)) && isAlphanumeric(s.charAt(tail))) {
                    if(lowCase(s.charAt(head)) == lowCase(s.charAt(tail))){
                        head++;
                        tail--;
                    } else {
                        return false;
                    }
                }
             
            }
            return true;
            
            
        }
    }

  • 0
    S

    Same code for reference.

    public class Solution {
        public boolean isPalindrome(String s) {
            s = s.toLowerCase();
            int begin = 0, end = s.length()-1;
            while(begin < end){
                while(!isAlphanumeric(s.charAt(begin)) && begin < end) begin++;
                while(!isAlphanumeric(s.charAt(end)) && begin < end) end--;
                if(s.charAt(begin)!= s.charAt(end)) return false;
                begin++;
                end--;
            }
            return true;
        }
        
        public boolean isAlphanumeric(char c){
            return c >= '0' && c <='9' || c >= 'a' && c <= 'z';
        }
    }

  • 0
    L

    Much more concise. Thanks for sharing!


Log in to reply
 

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