Skip to content

Commit 976c4f8

Browse files
author
weiy
committed
word subsets medium
1 parent bd03550 commit 976c4f8

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

Array/WordSubsets.py

+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
"""
2+
We are given two arrays A and B of words. Each word is a string of lowercase letters.
3+
4+
Now, say that word b is a subset of word a if every letter in b occurs in a, including multiplicity. For example, "wrr" is a subset of "warrior", but is not a subset of "world".
5+
6+
Now say a word a from A is universal if for every b in B, b is a subset of a.
7+
8+
Return a list of all universal words in A. You can return the words in any order.
9+
10+
11+
12+
Example 1:
13+
14+
Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["e","o"]
15+
Output: ["facebook","google","leetcode"]
16+
Example 2:
17+
18+
Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["l","e"]
19+
Output: ["apple","google","leetcode"]
20+
Example 3:
21+
22+
Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["e","oo"]
23+
Output: ["facebook","google"]
24+
Example 4:
25+
26+
Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["lo","eo"]
27+
Output: ["google","leetcode"]
28+
Example 5:
29+
30+
Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["ec","oc","ceo"]
31+
Output: ["facebook","leetcode"]
32+
33+
34+
Note:
35+
36+
1 <= A.length, B.length <= 10000
37+
1 <= A[i].length, B[i].length <= 10
38+
A[i] and B[i] consist only of lowercase letters.
39+
All words in A[i] are unique: there isn't i != j with A[i] == A[j].
40+
41+
42+
如果 B 中每一个元素出现的字符均在 A 中某一个元素中出现,则视为子单词,给一个A 和 B求子单词数量。
43+
44+
思路:
45+
哈希 A,
46+
哈希 B。
47+
48+
B 哈希的时候要注意,有重复。
49+
50+
比如["ec","oc","ceo"]
51+
只要有 c e o 各一次即可。不需要每个都判断一次。
52+
53+
测试地址:
54+
https://leetcode.com/problems/word-subsets/description/
55+
56+
这个写法比较慢,前面的思路基本都是哈希。
57+
58+
"""
59+
from collections import Counter
60+
61+
class Solution(object):
62+
def wordSubsets(self, A, B):
63+
"""
64+
:type A: List[str]
65+
:type B: List[str]
66+
:rtype: List[str]
67+
"""
68+
dict_A = {i:Counter(i) for i in A}
69+
dict_B = {}
70+
71+
for i in B:
72+
c = Counter(i)
73+
for j in c:
74+
if c.get(j) > dict_B.get(j, 0):
75+
dict_B[j] = c.get(j)
76+
77+
result = []
78+
79+
for i in dict_A:
80+
for j in dict_B:
81+
if dict_B[j] > dict_A[i].get(j):
82+
break
83+
else:
84+
result.append(i)
85+
86+
return result

0 commit comments

Comments
 (0)