判断句子是否为全字母【LC1832】
A pangram is a sentence where every letter of the English alphabet appears at least once.
Given a string
sentencecontaining only lowercase English letters, returntrueifsentenceis a pangram, orfalseotherwise.
居“家”的第一天 冲
哈希表
-
思路:首先当字符串为全字母排列时,其长度一定大于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的二进制数字,它的第iii位对应字母表的第iii个字母,当为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)
- 复杂度

本文介绍了一种算法,用于判断一个给定的英文句子是否包含英语字母表中的每一个字母至少一次。通过两种方法实现:哈希表和位运算,并分析了它们的时间与空间复杂度。
929

被折叠的 条评论
为什么被折叠?



