-
Notifications
You must be signed in to change notification settings - Fork 43
/
word-subsets.py
51 lines (49 loc) · 1.32 KB
/
word-subsets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/82914193
class Solution(object):
def wordSubsets(self, A, B):
"""
:type A: List[str]
:type B: List[str]
:rtype: List[str]
"""
B = set(B)
res = []
count = collections.defaultdict(int)
for b in B:
cb = collections.Counter(b)
for c, v in cb.items():
count[c] = max(count[c], v)
res = []
for a in A:
ca = collections.Counter(a)
isSuccess = True
for c, v in count.items():
if v > ca[c]:
isSuccess = False
break
if isSuccess:
res.append(a)
return res
# V2
# Time: O(m + n)
# Space: O(1)
import collections
class Solution(object):
def wordSubsets(self, A, B):
"""
:type A: List[str]
:type B: List[str]
:rtype: List[str]
"""
count = collections.Counter()
for b in B:
for c, n in collections.Counter(b).items():
count[c] = max(count[c], n)
result = []
for a in A:
count = collections.Counter(a)
if all(count[c] >= count[c] for c in count):
result.append(a)
return result