带移位和运算符的独特字符:不明白这段代码 [英] unique chars with shift and operators : don't understand this code
问题描述
我不理解循环中的行:我们取字符并减去 a
,所以10? (为什么?)
然后 1<< val
:我们将val换成1? (为什么?)
和检查器是0,那么我们如何达到> 0
条件?
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;
}
谢谢
推荐答案
该代码假定 str
由小写字母组成,如果没有重复字母则返回true。它的工作方式如下:
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
用作位图,即使用此变量中的每个位跟踪一个字母。从字符中减去'a'为'a'提供0,为'c'提供1,为'c'提供2等等。将此数字向左移1表示'a'为1,'b'为2,'c为4 '等。
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.
通过oring( |
)这个值与 checker
代码跟踪以前遇到的字符。所以,如果我们遇到第二个'a',例如, checker
它的第一个位设置(由& $ c $测试c>在if语句中),所以我们知道
str
有重复。
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.
简而言之, checker
用作更快更紧凑的bool数组。这种和类似的技术称为位操作。
In short, checker
is used as a faster and more compact array of bool. This and similar techniques are called bit manipulation.
这篇关于带移位和运算符的独特字符:不明白这段代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!