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 question is quite old but I think my answer is correct and clearer. We are dealing with lower case letter only in this case. Like Paul asked,
(1 << val)
means Shift 1 by 'val' not shift 'val' by one. So for example, 'hello' gives:I hope this clears things. I have the source code if you'd like to see exactly what's happening.
str.charAt(i) - 'a'
returns, more or less, the "letter in the alphabet": ifstr.charAt(i)
is'a'
, this is0
, if it's'b'
,val
is1
, if it'sz
,val
is25
, and so on.The rest of this is using a bit-twiddling technique: if the
val
th bit ofchecker
is1
, then we've seen theval
th character already. Sochecker & (1 << val)
is nonzero if and only if theval
th bit ofchecker
is set, meaning we've already seen that character. Otherwise, we set theval
th bit ofchecker
and continue the loop.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 withchecker
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 thatstr
has duplicates.In short,
checker
is used as a faster and more compact array of bool. This and similar techniques are called bit manipulation.