4ms Java solution beats 99%


  • 0
    M
    public class Solution {
       private static boolean[] isAlphaOrNum = new boolean[Character.MAX_VALUE];
    	private static int sub = 'a' - 'A';
    	static {
    		for (int i = 'a'; i <= 'z'; i++)
    			isAlphaOrNum[i] = true;
    		for (int i = 'A'; i <= 'Z'; i++)
    			isAlphaOrNum[i] = true;
    		for (int i = '0'; i <= '9'; i++)
    			isAlphaOrNum[i] = true;
    	}
    	public boolean isPalindrome(String s) {
            int lo = 0, hi = s.length() - 1;
            char[] a = s.toCharArray();
            while (lo < hi) {
            	while (lo < hi && !isAlphaOrNum[a[lo]])  lo++;
            	while (lo < hi && !isAlphaOrNum[a[hi]])  hi--;
            	if (lo < hi && !isPalindrome(a[lo], a[hi])) {
            		return false;
            	}
            	lo++;hi--;	
            }
            return true;
        }
    	
    	private boolean isPalindrome(char c1, char c2) {
    		if (c1 == c2)
    			return true;
    		else {
    			int max, min;
    			if (c1 > c2) {
    				max = c1;
    				min = c2;
    			}
    			else {
    				max = c2;
    				min = c1;
    			}
    			if (min < 'A')
    				return false;
    			else if (max - min == sub)
    				return true;
    		}
    		return false;
    	}
    
    
    }
    

Log in to reply
 

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