这个问题很老了,但我认为我的回答是正确和清晰的。我们只在这种情况下处理小写字母。就像保罗问的那样,(1 << val)
意味着 Shift 1 by 'val' 而不是 shift 'val' 。例如,'hello' 给出:
1st loop: val = 111 in binary, 7 in decimal
1 << val = 10000000 <-- here one is shifted by 7
checker = 10000000
2nd loop: val = 100 in binary, 4 in decimal
1 << val = 10000
checker = 10010000
3rd loop: val = 1011 in binary, 11 in decimal
1 << val = 100000000000
checker = 100010010000
4th loop: val = 1011 in binary, 11 in decimal
1 << val = 100000000000
(checker & (1 << val)) gives 100000000000 which is greater than 0
The loop is over because 'l' is not unique after 'hel' in 'hello'.
我希望这能解决问题。如果你想看看到底发生了什么,我有源代码。
public class one_one_one {
public static void main(String[] args) {
String chars = "hello";
if (isUniqueChars(chars)) {
System.out.println("Unique");
} else {
System.out.println("Not Unique");
}
}
public static boolean isUniqueChars(String str) {
int checker = 0;
for (int i = 0; i < str.length(); i++) {
int val = str.charAt(i) - 'a';
System.out.println(Integer.toBinaryString(val)); //debug printout
int temp = 1 << val;
System.out.println(Integer.toBinaryString(temp)); //debug printout
System.out.println(checker & (1 << val)); //debug printout
if ((checker & (1 << val)) > 0) {
return false;
}
checker |= (1 << val);
System.out.println(Integer.toBinaryString(checker)); //debug printout
System.out.println(' '); //debug printout
}
return true;
}
}