Clean Java solution. A must see. Comments included.


  • -1
    P
    public boolean isPalindrome(String s) { //Efficient than using regex because you can skip one whole pass.
    		if (s.length() == 0)
    			return true;
    		int i = 0;
    		int j = s.length() - 1;
    		s = s.toLowerCase();
    		while(i < j) {
    			while(i < s.length() && !valid(s.charAt(i))) //move until you are on a valid char
    				i++;
    			while(j >= 0 && !valid(s.charAt(j)))
    				j--;
    			if(i < s.length() && j >=0 && s.charAt(i) != s.charAt(j))
    				return false;
    			i++;
    			j--;
    		}
    
    		return true;
    	}
    private boolean valid(char x) { 
    		if (((x <= 'z') && (x >= 'a')) || ((x <= '9') && (x >= '0')))
    			return true;
    		return false;
    	}
    

Log in to reply
 

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