So far, i have came up with this. I have tried to minimize string operations and isolate solution to built in data types, arrays and integer operations.
I'm in search of much more elegant way to check for a pangram string, in java.
Elegant, as in minimum lines of code, other efficient algorithms are also welcome.
Please provide suggestions without lambda expressions.
private static boolean isPangrams(String ip) {
char[] characterArray = ip.toLowerCase().toCharArray();
int map[] = new int[26];
int sum = 0;
for(char current : characterArray) {
int asciiCode = (int) current;
if (asciiCode >= 97 && asciiCode <= 122) {
if (map[122 - asciiCode] == 0) {
sum += 1;
map[122 - asciiCode] = 1;
}
}
}
return sum == 26;
}
You can use bitwise operations for that:
private static boolean isPangrams(String ip) {
int flags = 0;
for(char current : ip.toLowerCase().toCharArray()) {
if (current >= 'a' && current <= 'z') {
flags |= 0x01<<(current-'a');
}
}
return flags == 0x3ffffff;
}
The code works as follows: we consider an int which is a 32-bit number. Each bit up to 26 is a flag (a boolean
so to speak). Initially all flags are false
because we initialize flags
with 0
.
Now we iterate over the characters of the string. In case the character is a lowercase letter, we set the flag of the corresponding flag to true
(regardless whether it has been set to true
before).
Finally we inspect whether the lowest 26 bits are all set to true
. If so, flags
is equal to 0x3ffffff
(which is a hexadecimal number equal to 1111111111111111111111
binary. If so we return true
. Otherwise we return false
.
Usually bitwise operations are faster than if
statements and booleans so I expect this program to be a significant bit faster.