高效的Java语言构造来检查字符串是否为pangram? [英] Efficient Java language constructs to check if string is pangram?

查看:139
本文介绍了高效的Java语言构造来检查字符串是否为pangram?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我已经想到了这一点.我试图最小化字符串操作,并将解决方案隔离到内置的数据类型,数组和整数操作中.

So far, i have came up with this. I have tried to minimize string operations and isolate solution to built in data types, arrays and integer operations.

我正在寻找一种更优雅的方式来检查Java中的pangram字符串.

I'm in search of much more elegant way to check for a pangram string, in java.

优雅,就像最少的代码行一样,也欢迎使用其他有效的算法.

Elegant, as in minimum lines of code, other efficient algorithms are also welcome.

请提供不带lambda表达式的建议.

Please provide suggestions without lambda expressions.

    private static boolean isPangrams(String ip) {

        char[] characterArray = ip.toLowerCase().toCharArray();
        int map[] = new int[26];
        int sum = 0;

        for(char current : characterArray) {

            int asciiCode = (int) current;
            if (asciiCode >= 97 && asciiCode <= 122) {

                if (map[122 - asciiCode] == 0) {

                    sum += 1;
                    map[122 - asciiCode] = 1;
                }
            }
        }

        return sum == 26;
    }

推荐答案

您可以为此使用按位运算:

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;
}

jDoodle

代码的工作方式如下:我们认为一个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.

这篇关于高效的Java语言构造来检查字符串是否为pangram?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆