Leetcode 1832. Check if the Sentence Is Pangram
A pangram is a sentence where every letter of the English alphabet appears at least once.
Given a string sentence
containing only lowercase English letters, return true
if sentence
is a pangram, or false
otherwise.
Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
Output: true
Explanation: The sentence contains at least one of every letter of the English alphabet.
Input: sentence = "leetcode"
Output: false
sentence
can be large, but for practical purposes, we might assume up to around 10^4 characters since it’s feasible to handle such strings in memory.We can solve this problem using a set to track which characters we have encountered in the sentence. The idea is to:
true
; otherwise, return false
.This approach works because the set automatically handles duplicates and ensures that only unique characters are counted.
import java.util.HashSet;
import java.util.Set;
public class Solution {
public boolean checkIfPangram(String sentence) {
// A set to keep track of unique characters
Set<Character> uniqueCharacters = new HashSet<>();
// Iterate over each character in the sentence
for (char c : sentence.toCharArray()) {
uniqueCharacters.add(c);
}
// There are 26 letters in the English alphabet
return uniqueCharacters.size() == 26;
}
public static void main(String[] args) {
String sentence1 = "thequickbrownfoxjumpsoverthelazydog";
String sentence2 = "leetcode";
Solution sol = new Solution();
System.out.println(sol.checkIfPangram(sentence1)); // Output: true
System.out.println(sol.checkIfPangram(sentence2)); // Output: false
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?