LeetCode 1832. 判断句子是否为全字母句

该博客探讨了如何通过位运算优化LeetCode中关于判断全字母句的问题。提供了几种不同的C++实现方案,包括使用set和unordered_set数据结构,以及使用位运算在不超过26次检查的情况下确定字符串是否包含所有字母。位运算解决方案通过设置一个整数并使用位移操作符检查每个字符,当所有26个二进制位都被设置时,表明字符串是全字母句。
摘要由CSDN通过智能技术生成

LeetCode

全字母句 指包含英语字母表中每个字母至少一次的句子。

给你一个仅由小写英文字母组成的字符串 sentence ,请你判断 sentence 是否为 全字母句 。

如果是,返回 true ;否则,返回 false 。

示例 1:
输入:sentence = “thequickbrownfoxjumpsoverthelazydog”
输出:true
解释:sentence 包含英语字母表中每个字母至少一次。

示例 2:
输入:sentence = “leetcode”
输出:false

提示:
1 <= sentence.length <= 1000
sentence 由小写英语字母组成

==============

思路:

  1. 字母有对应的数值,且是连续的,可以利用数组结构去重。
  2. 利用set数据结构去重。
  3. 长度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();
    }
};

另外看到的其他解法

  1. 最简洁
class Solution {
public:
    bool checkIfPangram(string s) {
        return 26 == std::unordered_set<char>(s.begin(), s.end()).size();
    }
};
  1. 位运算
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
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值