What would be the best logic to check all the letters in a given string.
If all the 26 letters are available in the provided string, I want to check that and perform
I'd go for a bitmap. If you increment a counter each time you set an entry in the bitmap to 1, you can early return as soon as you've seen all the letters. I hope this is not for enforcing password requirements.
I'd go for a sieve algorithm on the 26 letters. Just my $.02.
Edit: An array of 26 values that represent the 26 letters of the alphabet. Then scan the string, checking each letter as you encounter it. At the end, check if the 26 letters have been checked.
An array of 26 booleans is enough, each entry representing on of the alphabet letters. You can set the entry to true when the letter is found.
Explanation
First I will convert all string chars to uppercase.
in ASCII Table you can find uppercase chars ranges, i.e. between 65 to 90
A == 65 and Z == 90
So, for
loop should start from 65 and end on 90.
Check if the string contains current ASCII char.
I am converting integer to char and put "" to be string
if !text.contains((char)i + "") == true
This implies that if the string does not have the current char to i
, I will return false
.
You can make it even better by using char i
in loop
static boolean isPangram(String text) {
//change all chars to upper case
text = text.toUpperCase();
//Loop from A to Z
for(int i = 65 ; i < 91 ; i++){
//if text not contains return false
if(!text.contains((char)i + "")){
return false;
}
}
return true;
}
Using a BitMap, I'm assuming you meant case insenstive.
Update: Solution by Thomas is more efficient, than the following. :) Use that one.
//
String test = "abcdefeghjiklmnopqrstuvwxyz";
BitSet alpha = new BitSet(26);
for(char ch : test.toUpperCase().toCharArray())
if(Character.isLetter(ch))
alpha.set(ch - 65);
System.out.println(alpha.cardinality() == 26);
Not yet fully optimized:
public static void main(String... a) {
String s = "Pack my box with five dozen liquor jugs.";
int i=0;
for(char c : s.toCharArray()) {
int x = Character.toUpperCase(c);
if (x >= 'A' && x <= 'Z') {
i |= 1 << (x - 'A');
}
}
if (i == (i | ((1 << (1 + 'Z' - 'A')) - 1))) {
System.out.println("ok");
}
}