统计一致字符串的数目
问题描述:
给你一个由不同字符组成的字符串 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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。