开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第8天,点击查看活动详情
1832. 判断句子是否为全字母句
一、题目描述:
全字母句 指包含英语字母表中每个字母至少一次的句子。
给你一个仅由小写英文字母组成的字符串 sentence ,请你判断 sentence 是否为 全字母句 。
如果是,返回 **true ;否则,返回 **false 。
示例 1:
输入: sentence = "thequickbrownfoxjumpsoverthelazydog"
输出: true
解释: sentence 包含英语字母表中每个字母至少一次。
示例 2:
输入: sentence = "leetcode"
输出: false
提示:
1 <= sentence.length <= 1000sentence由小写英语字母组成
二、思路分析:
- 使用长度为26的数组记录每个字符是否出现过
遍历字符串 sentence,用数组记录出现过的字母,最后判断数组中是否有 26 个字母即可。
具体的,我们遍历 sentence 中的每个字符 c,如果 c 是字母表中的第 i 个字母,就将 map[i] 置为 true。最后检查 map 中是否存在 false,如果存在返回 false,否则返回 true.
时间复杂度 O(n),空间复杂度 O(C)
- 二进制压缩,使用一个int数字记录状态
用一个整数 state 记录出现过的字母,其中 state 的第 i 位表示第 i 个字母是否出现过。
最后判断 state 的二进制表示中是否有 26 个 1
时间复杂度 O(n),空间复杂度 O(1)
三、AC 代码:
- 方案一:使用数组
class Solution {
public boolean checkIfPangram(String sentence) {
boolean[] map = new boolean[26];
char[] chs = sentence.toCharArray();
for (char c : chs){
map[c -'a'] = true;
}
for (boolean b : map){
if (!b) return false;
}
return true;
}
}
方案二 : 二进制数字
class Solution {
public boolean checkIfPangram(String sentence) {
int state = 0;
char[] chs = sentence.toCharArray();
for (char c : chs) {
state |= 1 << (c - 'a');
}
for (int i = 0; i < 26; i++) {
if (((state >> i) & 1) != 1) return false;
}
return true;
}
}