第十七天统计一致字符串的数目

统计一致字符串的数目

问题描述:
给你一个由不同字符组成的字符串 allowed 和一个字符串数组 words 。如果一个字符串的每一个字符都在 allowed 中,就称这个字符串是 一致字符串 。

请你返回 words 数组中 一致字符串 的数目。

示例 1:

输入:allowed = “ab”, words = [“ad”,“bd”,“aaab”,“baa”,“badab”]
输出:2
解释:字符串 “aaab” 和 “baa” 都是一致字符串,因为它们只包含字符 ‘a’ 和 ‘b’ 。

问题求解:

class Solution:
    def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
        return sum([set(word) <= set(allowed) for word in words])

问题总结:
老规矩我们先看一下官方求解。
方法一:遍历
由题意可知,字符串 \textit{allowed}allowed 和字符串数组 \textit{words}words 中的所有字符串都只包含小写字母,因此我们可以用一个 3232 位整数来表示一个字符串出现的字母集合。如果一个字母出现了,那么将对应整数的位设为 11。使用 \textit{mask}mask 表示字符串 \textit{allowed}allowed 出现的字母集合。依次遍历字符串数组 \textit{words}words,假设第 ii 个字符串 \textit{words}[i]words[i] 对应出现的字母集合为 \textit{mask}_1mask
1

,那么 \textit{words}[i]words[i] 是一致字符串等价于 \textit{mask}_1mask
1

是 \textit{mask}mask 的子集,即 \textit{mask}_1 \cup \textit{mask} = \textit{mask}mask
1

∪mask=mask。统计一致字符串的数目并返回结果。

作者:LeetCode-Solution
链接:https://leetcode.cn/problems/count-the-number-of-consistent-strings/solution/tong-ji-yi-zhi-zi-fu-chuan-de-shu-mu-by-38356/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值