全字母句 指包含英语字母表中每个字母至少一次的句子。
给你一个仅由小写英文字母组成的字符串 sentence ,请你判断 sentence 是否为 全字母句 。
如果是,返回 true ;否则,返回 false 。
示例 1:
输入:sentence = “thequickbrownfoxjumpsoverthelazydog”
输出:true
解释:sentence 包含英语字母表中每个字母至少一次。
示例 2:
输入:sentence = “leetcode”
输出:false
提示:
1 <= sentence.length <= 1000
sentence 由小写英语字母组成
==============
思路:
- 字母有对应的数值,且是连续的,可以利用数组结构去重。
- 利用set数据结构去重。
- 长度1000,最少检测26次就可以,不需要全部检测。
第一次
class Solution {
public:
bool checkIfPangram(string sentence) {
std::set<char> alphabet;
for(auto c : sentence) {
alphabet.insert(sentence[c]);
}
return 26 == alphabet.size();
}
};
减少检测次数
class Solution {
public:
bool checkIfPangram(string sentence) {
std::set<char> alphabet;
for(auto i = 0; i < sentence.length(); ++i) {
if (i >= 26 and 26 == alphabet.size()) return true;
alphabet.insert(sentence[i]);
}
return 26 == alphabet.size();
}
};
unordered_set不需要排序,比set效率更高。
class Solution {
public:
bool checkIfPangram(string sentence) {
std::unordered_set<char> alphabet;
for(auto i = 0; i < sentence.length(); ++i) {
if (i >= 26 and 26 == alphabet.size()) return true;
alphabet.insert(sentence[i]);
}
return 26 == alphabet.size();
}
};
另外看到的其他解法
- 最简洁
class Solution {
public:
bool checkIfPangram(string s) {
return 26 == std::unordered_set<char>(s.begin(), s.end()).size();
}
};
- 位运算
class Solution {
public:
bool checkIfPangram(string sentence) {
int res = 0;
for (auto c : sentence)
res |= (1 << (c - 'a'));
return res == ((1 << 26) - 1); //即低26位全是1
}
};