判断句子是否为全字母【LC1832】
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, returntrue
ifsentence
is a pangram, orfalse
otherwise.
居“家”的第一天 冲
哈希表
-
思路:首先当字符串为全字母排列时,其长度一定大于26;然后使用哈希表数组记录该字母是否出现过,每次出现一个新字母时,整型变量
count
加1;最后当count==26
时,返回true
-
实现
class Solution { public boolean checkIfPangram(String sentence) { if (sentence.length() < 26){ return false; } int count = 0; boolean[] map = new boolean[26]; for (char c : sentence.toCharArray()){ if (!map[c - 'a']){ count++; map[c - 'a'] = true; } } return count == 26; } }
- 复杂度
- 时间复杂度: O ( n ) O(n) O(n),n为字符串长度
- 空间复杂度: O ( C ) O(C) O(C)
- 复杂度
位运算
-
思路:使用一个
int
类型的变量state
代替哈希表,该变量是长度为26的二进制数字,它的第 i i i位对应字母表的第 i i i个字母,当为1时代表该字母存在;最后当state
的所有位均为1时,返回true
-
实现
class Solution { public boolean checkIfPangram(String sentence) { if (sentence.length() < 26){ return false; } int state = 0; for (char c : sentence.toCharArray()){ state |= 1 << c - 'a'; } return state == (1 << 26) - 1; } }
- 复杂度
- 时间复杂度: O ( n ) O(n) O(n),n为字符串长度
- 空间复杂度: O ( 1 ) O(1) O(1)
- 复杂度