AC hashing as a alternative solution


  • 0
    A

    In real world when the hashes are equal you need to do a proper check but it was enough to pass the tests here.

    public boolean isPalindrome(String s) {
        return hash(s,true) == hash(s,false);
    }
    
    private int hash(String s, boolean dir) {
    	int h = 0;
    	int length = s.length()-1;
    	for (int i = 0; i <= length; i++) {
    		char c = s.charAt(dir ? i : length-i);
    		if( Character.isLetterOrDigit(c) )
    			h = 31 * h + Character.toLowerCase(c);
    	}
        return h;
    }

Log in to reply
 

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