Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unique chars with shift and operators : don't understand this code

i don't understand the lines in the loop : we take the character and subtract a, so "10" ? (why?)
then 1 << val : we shift 1 by val ? (why?)
and checker is 0, so how do we reach > 0 in the condition?

    public static boolean isUniqueChars(String str) {
    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;
}

Thanks

like image 259
Paul Avatar asked Dec 27 '22 00:12

Paul


1 Answers

The code assumes that str is made of lower case letters and returns true if there are no repeating letters. It works like this:

checker is used as a bitmap, that is, each bit in this variable is used to keep track of one letter. Subtracting 'a' from the character gives 0 for 'a', 1 for 'b', 2 for 'c' etc. Shifting 1 left by this number gives 1 for 'a', 2 for 'b', 4 for 'c' etc.

By oring (|) this value with checker the code keeps track of previously encountered characters. So, if we encounter a second 'a' for example, checker has it's first bit set (which is tested by & in the if statement), so we know that str has duplicates.

In short, checker is used as a faster and more compact array of bool. This and similar techniques are called bit manipulation.

like image 58
cyco130 Avatar answered May 01 '23 06:05

cyco130