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?
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
acharacter, eg'e' - 'a' = 5. This distance is used to set (throughchecker |= (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 forchecker.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.