我的任务如下:
编写一个方法,该方法将连续(递增)字母数组作为输入,并返回数组中缺少的字母。
您总是会得到一个有效的数组。而且总是有一个字母不见了。数组的长度将始终至少为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”不见了,尽管我没有提供所有字母的数组?