Problem: 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.
Example:
Input: sentence = "thequickbrownfoxjumpsoverthelazydog" Output: true Explanation: sentence contains at least one of every letter of the English alphabet.
Input: sentence = "leetcode" Output: false
Approach: We can use HashSet here, basically we will keep adding the characters of the sentence in HashSet. HashSet will ensure the uniqueness. In the end we can check the size of HashSet, if it is 26 then all the letters of english alphabets are present so we can true; false otherwise.
Given its only 26 characters, we can achieve the same thing using an bool array and an int variable. You can understand the approach by just looking at the implementation.
Implementation in C#:
public bool CheckIfPangram(string sentence)
{
bool[] flag = new bool[26];
int sum = 0;
foreach (char ch in sentence)
{
if (!flag[ch - 'a'])
{
flag[ch - 'a'] = true;
++sum;
}
}
return sum == 26;
}
Complexity: O(n)
No comments:
Post a Comment