一、题目
给你一个由不同字符组成的字符串 allowed 和一个字符串数组 words 。如果一个字符串的每一个字符都在 allowed 中,就称这个字符串是 一致字符串 。
请你返回 words 数组中 一致字符串 的数目。
来源:力扣
二、思路
1.依次遍历words中的字符串的每个字符与allowed进行比较,相同count+1
2.嵌套for循环,利用sum函数进行计数
三、代码
方法一:
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
count=0
for i in words:
for k,m in enumerate(i):
for j,l in enumerate(allowed):
if m==l and k!=len(i)-1:
break
elif m!=l and j==len(allowed)-1:
break
elif m==l and k==len(i)-1:
count+=1
if m!=l and j==len(allowed)-1:
break
return count
方法二:
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
s = set(allowed)
return sum(all(c in s for c in w) for w in words)