更新时间:2021-08-20 07:16:31
您可以为此使用按位运算:
You can use bitwise operations for that:
private static boolean isPangrams(String ip) {
int flags = 0;
for(char current : ip.toLowerCase().toCharArray()) {
if (current >= 'a' && current <= 'z') {
flags |= 0x01<<(current-'a');
}
}
return flags == 0x3ffffff;
}
代码的工作方式如下:我们认为一个int是32位数字.直到26位的每个位都是一个标志(可以说是boolean
).最初,所有标志都是false
,因为我们用0
初始化了flags
.
The code works as follows: we consider an int which is a 32-bit number. Each bit up to 26 is a flag (a boolean
so to speak). Initially all flags are false
because we initialize flags
with 0
.
现在,我们遍历字符串的字符.如果字符是小写字母,则将相应标志的标志设置为true
(无论之前是否已将其设置为true
).
Now we iterate over the characters of the string. In case the character is a lowercase letter, we set the flag of the corresponding flag to true
(regardless whether it has been set to true
before).
最后,我们检查最低的26位是否都设置为true
.如果是,则flags
等于0x3ffffff
(这是一个等于1111111111111111111111
二进制的十六进制数.如果是,则返回true
.否则返回false
.
Finally we inspect whether the lowest 26 bits are all set to true
. If so, flags
is equal to 0x3ffffff
(which is a hexadecimal number equal to 1111111111111111111111
binary. If so we return true
. Otherwise we return false
.
通常,按位运算比if
语句和布尔值更快,因此我希望该程序要快得多.
Usually bitwise operations are faster than if
statements and booleans so I expect this program to be a significant bit faster.