力扣-1684. 统计一致字符串的数目

本文最后更新于:2022年11月8日 晚上

题目描述

1684

思路及实现

既然是要让我们判断words中的每个word中的每个字母有没有在allowed中出现(存在),那就是要涉及到遍历word的同时遍历allowed
那倒不如先用一个哈希表把allowed中的每个字母都存进去,因为allowed中的字母是不会重复的,而且这样可以把遍历变成检索,减小时间复杂度。

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
alpha_dict = {}
ans = 0
for alpha in allowed: # 用个字典保存 allowed 中的字符,之后检索就能加快
alpha_dict[alpha] = 1
for word in words:
for a in word:
if a not in alpha_dict:
ans -= 1
break
ans += 1
return ans

上面是第一个版本,最猪的一个,用字典存,您完全把集合忘掉了是吗(
下面是换成集合的,其实没差啦(

1
2
3
4
5
6
7
8
9
10
11
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
alpha_set = set(allowed)
ans = 0
for word in words:
for a in word:
if a not in alpha_set:
ans -= 1
break
ans += 1
return ans

再甚就直接利用特性了:

1
2
3
4
5
6
7
8
9
10
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
ans = 0
for word in words:
for a in word:
if a not in allowed:
ans -= 1
break
ans += 1
return ans

(看到个内存使用0.几的,一看代码直接是用的issubset(),这是什么呢?“issubset()方法用于判断集合的所有元素是否都包含在指定集合中,如果是则返回 True,否则返回 False。”,有学到,谢谢这位大佬


这里有一只爱丽丝

希望本文章能够帮到您~


力扣-1684. 统计一致字符串的数目
https://map1e-g.github.io/2022/11/08/leetcode-1684/
作者
MaP1e-G
发布于
2022年11月8日
许可协议