I am not really sure how this code works:
public static boolean isUniqueChar2(String str) {
int checker = 0;
for (int i = 0; i < str.length(); ++i) {
int val = str.charAt(i) - 'a';
System.out.println(str.charAt(i) );
System.out.println(val);
if ((checker & (1 << val)) > 0)
return false;
checker |= (1 << val);
}
return true;
}
In particular I do not understand particular >> operator and the role of checker
It looks like this method is only designed to work for lower-case letters. The checker
variable is a 32-bit bitmap initialized to all 0
s. The code 1 << val
takes a 1 and shifts it into the position of val
, which represents a letter of the alphabet (a=0, b=1, c=2, etc.). if ((checker & (1 << val)) > 0)
returns false
because any value other than 0 would indicate that a letter had been repeated. The last line in the loop, checker |= (1 << val);
sets the bit at position val
before the next iteration.
and | are bitwise shift and binary or. I suggest you do some reading of binary and bitwise operator: http://en.wikipedia.org/wiki/Bitwise_operation
a |= b is just a shorthand of a = a | b similar like a += b to a = a + b
来源:https://stackoverflow.com/questions/13982314/java-operator-find-if-characters-are-unique