Check If a String Contains All The Letters of The Alphabet with Java – 用Java检查一个字符串是否包含所有的英文字母

最后修改: 2018年 9月 4日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial,  we’ll see how to check if a String contains all the letters of the alphabet or not.

在本教程中,我们将看到如何检查一个字符串是否包含所有的英文字母。

Here’s a quick example: “Farmer jack realized that big yellow quilts were expensive.” – which does actually contain all the letters of the alphabet.

这里有一个简单的例子。”农夫杰克意识到黄色大棉被很贵。” –这实际上包含了字母表的所有字母。

We’ll discuss three approaches.

我们将讨论三种方法。

First, we’ll model the algorithm using an imperative approach. Then will use regular expressions. And finally, we’ll take advantage of a more declarative approach using Java 8.

首先,我们将使用命令式方法对算法进行建模。然后将使用正则表达式。最后,我们将利用Java 8的更多声明性方法。

Additionally, we’ll discuss the Big-O-complexity of the approaches taken.

此外,我们将讨论所采取的方法的大O复杂性。

2. Imperative Algorithm

2.势在必行的算法

Let’s implement an imperative algorithm. For this, first, we’ll create a boolean array visited. Then, we’ll walk through input string character by character and mark the character as visited.

让我们来实现一个命令式的算法。为此,首先,我们将创建一个布尔数组visited。然后,我们将逐个走过输入的字符串,并将该字符标记为已访问。

Please note that Uppercase and Lowercase are considered the same. So index 0 represents both A and a, likewise, index 25 represents both Z and z.

请注意,大写小写被认为是一样的。因此,索引0同时代表A和a,同样,索引25同时代表Z和z。

Finally, we’ll check if all the characters in the visited array are set to true:

最后,我们将检查访问的数组中的所有字符是否被设置为真。

public class EnglishAlphabetLetters {

    public static boolean checkStringForAllTheLetters(String input) {
        int index = 0;
        boolean[] visited = new boolean[26];

        for (int id = 0; id < input.length(); id++) {
            if ('a' <= input.charAt(id) && input.charAt(id) <= 'z') {
                index = input.charAt(id) - 'a';
            } else if ('A' <= input.charAt(id) && input.charAt(id) <= 'Z') {
                index = input.charAt(id) - 'A';
            }
            visited[index] = true;
        }

        for (int id = 0; id < 26; id++) {
            if (!visited[id]) {
                return false;
            }
        }
        return true;
    }
}

Big-O-complexity of this program is O(n) where n is the length of the string.

这个程序的大O复杂度是O(n),其中n是字符串的长度。

Note that there are many ways to optimize the algorithm, such as removing letters from a set and breaking as soon as the Set is empty. For the purpose of the exercise though, this algorithm is good enough.

请注意,有很多方法可以优化这个算法,比如从一个集合中删除字母,并在Set为空时立即中断。不过就本练习的目的而言,这种算法已经很好了。

3. Using Regular Expression

3.使用正则表达式

Using Regular expression, we can easily get the same results with a few lines of code:

使用正则表达式,我们只需几行代码就可以轻松得到同样的结果。

public static boolean checkStringForAllLetterUsingRegex(String input) {
    return input.toLowerCase()
      .replaceAll("[^a-z]", "")
      .replaceAll("(.)(?=.*\\1)", "")
      .length() == 26;
}

Here, we are first eliminating all the characters except alphabet letters from the input. Then we are removing duplicate characters. Finally, we are counting letters and making sure we have all of them, 26.

在这里,我们首先从输入中消除除字母以外的所有字符。然后,我们正在删除重复的字符。最后,我们正在计算字母,确保我们有所有的字母,26个。

Although less performant, Big-O-Complexity of this approach also tends to O(n).

虽然性能较差,但这种方法的Big-O-Complexity也趋向于O(n)。

4. Java 8 Stream

4.Java 8的流

Using Java 8 features, we can easily achieve the same result in a more compact and declarative way using Stream’s filter and distinct methods:

利用Java 8的特性,我们可以使用Stream的filterdistinct方法,以更紧凑和声明性的方式轻松实现同样的结果。

public static boolean checkStringForAllLetterUsingStream(String input) {
    long c = input.toLowerCase().chars()
      .filter(ch -> ch >= 'a' && ch <= 'z')
      .distinct()
      .count();
    return c == 26;
}

Big-O-complexity of this approach will also be O(n).

这种方法的大O复杂度也将是O(n)。

4. Testing

4.测试

Let’s test a happy path for our algorithm:

让我们为我们的算法测试一条快乐的路径。

@Test
public void givenString_whenContainsAllCharacter_thenTrue() {
    String sentence = "Farmer jack realized that big yellow quilts were expensive";
    assertTrue(EnglishAlphabetLetters.checkStringForAllTheLetters(sentence));
}

Here, sentence contains all the letters of the alphabet, hence, we’re expecting true as a result.

这里,sentence包含了所有的字母,因此,我们期待true作为结果。

5. Conclusion

5.结论

In this tutorial, we’ve covered how to check if a String contains all the letters of the alphabet.

在本教程中,我们已经介绍了如何检查一个字符串是否包含所有的字母.

We saw a couple of ways to implement this first using traditional imperative programming, regular expressions, and Java 8 streams.

我们看到有几种方法可以首先使用传统的命令式编程、正则表达式和Java 8流来实现这一点。

The complete source code is available over on GitHub.

完整的源代码可在GitHub上获得