确定字符串是否包含所有唯一字符的Java代码如何工作? [英] How does this Java code which determines whether a String contains all unique characters work?
问题描述
我有一个在网上找到的程序,该程序基本上可以告诉String
是否包含所有唯一字符,下面是代码
I have a program which I found online which basically tells whether the String
contains all unique characters, below is the code
private static boolean areCharsUnique(String str) {
if (str.length() > 256)
return false;
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;
}
我对这行代码if ((checker & (1 << val)) > 0)
和
checker |= (1 << val);
我知道<<
是左移运算符,但是在上述情况下左移到底有多大帮助呢?
I know that <<
is a left shift operator, but how exactly left shifting helps in the above situation?
简而言之,以上程序如何工作?
推荐答案
此代码在ASCII字符集在其映射中具有连续字符的前提下起作用,因此a == 97, b == 98
,依此类推.
This code works under the assumption that ASCII character set has consecutive character in its mapping so that a == 97, b == 98
, and so on.
从此开始,您可以计算与a
字符(例如'e' - 'a' = 5
)的距离差.此距离用于设置(通过checker |= (1 << val)
)整数(具有32位)中的一位.
Starting from this you can calculate a delta distance from the a
character, eg 'e' - 'a' = 5
. This distance is used to set (through checker |= (1 << val)
) a bit in a integer number (which has 32 bits).
因此,如果找到一个'e'
字符,那么checker
的索引5的位将设置为1.
So if a 'e'
character is found then bit at index 5 is set to 1 for checker
.
通过确保您永远不会(通过if (checker & (1 << val)) > 0)
)找到以前已经设置的位,对每个字符进行此操作.
This is done for every char by ensuring that you never find a bit that has been already set previously (through if (checker & (1 << val)) > 0)
).
这仅适用于小写字符(即使int具有32位). HashSet<Character>
肯定会更好.
This works only for lowercase characters (even because int has 32 bits). An HashSet<Character>
would be surely better.
这篇关于确定字符串是否包含所有唯一字符的Java代码如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!