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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With