字符如何工作以及与英文字母有何关系?

时间:2019-02-07 16:47:37

标签: java char

我的任务如下:

  

编写一种方法,该方法将连续(递增)字母数组作为输入,并返回数组中缺少的字母。

     

您将始终获得有效的数组。而且总是会丢失一个字母。数组的长度将始终至少为2。

     

仅在一种情况下,数组将始终包含字母。

     

示例:

['a','b','c','d','f'] -> 'e'
['O','Q','R','S'] -> 'P'

我真正不好的解决方案是:

public static char findMissingLetter(char[] array) {
    char[] alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

    int offset = 0;
    int point = 0;
    for (int i = 0; i < array.length; i++) {
        for (int j = 0; j < alphabet.length; j++) {
            if (alphabet[j] == array[i]) {
                offset = j;
                point = offset + 1;
                if (alphabet[point] != array[++i]) {
                    System.out.println(alphabet[point]);
                    return alphabet[point];
                }
            }
        }
    }
    return ' ';
}

现在我找到了一个非常短的解决方案,但是我不了解代码,或者至少我不了解如果不给代码提供可能的字母列表,它就能知道缺少的字母:

public static char findMissingLetter(char[] array){
    char expectedLetter = array[0];
    for(char letter : array){
        if(letter != expectedLetter) break;
        expectedLetter++;
    }
    return expectedLetter;
}

有人可以解释一下char的工作原理,为什么即使我没有提供所有字母的数组,它也知道缺少'e'?

2 个答案:

答案 0 :(得分:2)

您提供的解决方案非常简单。 您应该熟悉char值可解释为整数值,它是ASCII表中该特定字符的数字值。

因此,在采用expectedLetter的初始值(即char数组中的第一个值)之后的解决方案中,它将检查字符的数值。如果它们相同,则表示它们是相同的字符,因为系统会告诉您这些字符是连续的,并且只有一个字母大小写。因此,它将递增expectedLetter(这是ASCII表中的下一个字符,或者您可以按字母顺序说出下一个字符)的数值,然后再次检查该值,直到数组结尾。

答案 1 :(得分:1)

让我们使用以下示例进行说明:

['a','b','c','d','f'] -> 'e'

在Java中,char是数字类型。将1加到一个字符中时,将获得下一个Unicode代码点。对于“ A”,下一个代码点是“ B”。

public static char findMissingLetter(char[] array){
    char expectedLetter = array[0]; // This code initializes expectedLetter
                                    // with the first character in the array.
    for(char letter : array){
        // The first iteration will always be true. From the second iteration,
        // if the character is not the consecutive one which is expected to be
        // equal to expectedLetter then that letter will be the missing one.
        // Once found, break will close the loop and return that character.
        if(letter != expectedLetter) break;

        // This will increment character consecutively from a -> b -> c -> d -> e
        expectedLetter++;
    }

    return expectedLetter;
}