Problem overview
The method usesEveryLetter receives a string sentence made of lowercase letters and spaces. It returns true if every letter from a to z appears in it at least once, and false otherwise. Spaces are not letters, and a letter may appear many times.
The sentence "my jumpy dog fixed a big quiz with seven lucky parrots" has all 26 letters, so the answer is true. The sentence "six jumpy kittens quiz the brave fox and a wild hog" has 25 of them and no c, so the answer is false. The sentence "abc abc abc" has only three different letters, so the answer is false.
Approach
Collect the letters of the sentence in a HashSet. A set keeps each value once, however many times it is added, so after the loop the set holds exactly the different letters that appeared. Since the sentence has only lowercase English letters, there are 26 possible ones. If the set holds 26 letters, none is missing.
The one thing to watch is the space. It is a character too, so it would go in the set like any other. The code must keep spaces out.
Step by step
- Create an empty
HashSet<Character>namedletters. - Loop over the characters of the sentence with a
charnamedc, usingsentence.toCharArray(). - Inside the loop, check that
cis not a space. - Inside the
if, addctoletters. - After the loop, return whether
letters.size()is 26.
The solution in Java
class Solution {
public boolean usesEveryLetter(String sentence) {
HashSet<Character> letters = new HashSet<>();
for (char c : sentence.toCharArray()) {
if (c != ' ') {
letters.add(c);
}
}
return letters.size() == 26;
}
}
Some Java details:
- A set holds objects, so its type is
HashSet<Character>, notHashSet<char>. Java wraps eachcharinto aCharacterwhen you calladd. - A single character is written in single quotes,
' '. Double quotes would make a string, andc != " "would not compile. letters.size() == 26is alreadytrueorfalse, so the method returns it directly.
Following the second example: the loop adds the letters it meets, skipping the spaces, and ends with 25 different letters in the set. Only c is missing, so letters.size() == 26 is false. In the first example the set ends with all 26 letters, and the comparison is true.
Another way to think about it is that the set shrinks the sentence to its alphabet. Once you have the alphabet, the question becomes a simple count, and you don't need to check the letters one at a time against a to z.
Edge cases and common mistakes
- Letting the space in. Without the
if, the first example's set would hold 27 characters: 26 letters and the space. A full sentence would then fail the== 26test. The same bug would make a sentence with 25 letters and a space report 26 and wrongly returntrue. - Counting instead of collecting. The length of the sentence says nothing about the number of different letters.
- Repeated letters.
"abc abc abc"adds nine letters, but the set ends with three.
Testing
Running the solution on the three examples gives:
true
false
false
The tests print booleans in lowercase.
