LeetCode 1832: Check if the Sentence Is Pangram
Problem Description
Explanation:
To check if a given sentence is a pangram, we can iterate through each character in the sentence and mark its presence in a boolean array of size 26 (one for each alphabet letter). Once we have marked all the characters in the sentence, we check if all elements in the boolean array are true, indicating that all letters of the alphabet are present.
- Initialize a boolean array
isPresent
of size 26, all initially set to false. - Iterate through each character in the sentence.
- For each character, calculate its index in the boolean array by subtracting 'a' from the character and set the value at that index to true.
- After iterating through all characters, check if all elements in the
isPresent
array are true. - If all elements are true, return true; otherwise, return false.
Time Complexity: O(n) where n is the length of the input sentence.
Space Complexity: O(1) since the boolean array isPresent
is of constant size (26).
Solutions
class Solution {
public boolean checkIfPangram(String sentence) {
boolean[] isPresent = new boolean[26];
for (char c : sentence.toCharArray()) {
isPresent[c - 'a'] = true;
}
for (boolean present : isPresent) {
if (!present) {
return false;
}
}
return true;
}
}
Loading editor...