Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this Java code which determines whether a String contains all unique characters work? [duplicate]

Tags:

java

operators

I have a program which I found online which basically tells whether the String contains all unique characters, below is the code

private static boolean areCharsUnique(String str) {
        if (str.length() > 256)
            return false;
        int checker = 0;
        for (int i = 0; i < str.length(); i++) {
            int val = str.charAt(i) - 'a';
            if ((checker & (1 << val)) > 0) {
                return false;
            }
            checker |= (1 << val);
        }
        return true;
    }

I am baffled by this line of code if ((checker & (1 << val)) > 0) and also

checker |= (1 << val);

I know that << is a left shift operator, but how exactly left shifting helps in the above situation?

In short how does the above program work?

like image 978
Arif Nadeem Avatar asked Apr 18 '26 06:04

Arif Nadeem


1 Answers

This code works under the assumption that ASCII character set has consecutive character in its mapping so that a == 97, b == 98, and so on.

Starting from this you can calculate a delta distance from the a character, eg 'e' - 'a' = 5. This distance is used to set (through checker |= (1 << val)) a bit in a integer number (which has 32 bits).

So if a 'e' character is found then bit at index 5 is set to 1 for checker.

This is done for every char by ensuring that you never find a bit that has been already set previously (through if (checker & (1 << val)) > 0)).

This works only for lowercase characters (even because int has 32 bits). An HashSet<Character> would be surely better.

like image 154
Jack Avatar answered Apr 19 '26 19:04

Jack