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 1:
Input: sentence = “thequickbrownfoxjumpsoverthelazydog”
Output: true
Explanation: sentence contains at least one of every letter of the English alphabet.
Example 2:
Input: sentence = “leetcode”
Output: false
判断句子sentence中,是否含有所有的26个字母。
思路:
可用一个数组记录每个字母出现的次数,最后看是否有未出现的字母,如果有,返回false
public boolean checkIfPangram(String sentence) {
int[] cnt = new int[26];
for(int i = 0; i < sentence.length(); i++) {
cnt[sentence.charAt(i) - 'a'] ++;
}
for(int i = 0; i < 26; i++) {
if(cnt[i] == 0) return false;
}
return true;
}
上面这个方法要遍历一遍sentence,
然而字母只有26个,是不是只需要判断26个字母是否出现就可以了。
这样就只需要遍历26个字母。
public boolean checkIfPangram(String sentence) {
for(int i = 0; i < 26; i++) {
if(sentence.indexOf(i + 'a') == -1) return false;
}
return true;
}