According to your requirements, for a key to be valid, it must contain each letter of the [English] alphabet precisely once, since upper case letters and lower case letters are considered to be the same. In other words, if a key contains both a
and A
then it is invalid.
public static boolean encryptionKey(String key) {
boolean valid = key != null && key.length() == 26 && key.matches("^[a-zA-Z]+$");
if (valid) {
String str = key.toLowerCase();
boolean[] alphabet = new boolean[26];
char[] letters = str.toCharArray();
for (char letter : letters) {
int index = letter - 'a';
if (index >= 0 && index < 26) {
if (alphabet[index]) {
// repeated letter
valid = false;
break;
}
else {
alphabet[index] = true;
}
}
}
}
return valid;
}
Firstly, the method checks that the parameter is not null and contains exactly 26 characters and that each character is a letter of the [English] alphabet.
Then all the letters in the parameter are converted to lower case since a valid key is not case sensitive.
A char
is actually a number, so subtracting a
from a
gives 0 (zero). Subtracting a
from b
gives 1 (one) and so on.
A boolean array is implicitly initialized such that each element contains false
.
The code iterates through all the letters in the key
. If key
contains the letter a
(for example) then the first element in array alphabet
is set to true
. If the first array element is already true
, that means key
contains a
more than one time which is invalid.