代码之家  ›  专栏  ›  技术社区  ›  valik

char是如何工作的?它与英文字母有什么关系?

  •  2
  • valik  · 技术社区  · 5 年前

    我的任务如下:

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

    您总是会得到一个有效的数组。而且总是有一个字母不见了。数组的长度将始终至少为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 回复  |  直到 5 年前
        1
  •  1
  •   Boann    5 年前

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

    所以,在溶液中取初始值 expectedLetter (这是char数组中的第一个值),它检查字符的数值。如果它们是相同的,这意味着它们是相同的字符,正如您被告知的那样,字符是连续的,并且只有一个字母大小写。所以,它增加了 预期字母 (这是ASCII表中的下一个字符,或者您可以按字母顺序说出下一个字符),然后再次检查该值,直到数组结束。

        2
  •  1
  •   Boann    5 年前

    让我们用这个例子来解释:

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

    在爪哇中,字符是数字类型。当您向一个字符添加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;
    }