我们给出两个单词数组 A
和 B
。每个单词都是一串小写字母。
现在,如果 b
中的每个字母都出现在 a
中,包括重复出现的字母,那么称单词 b
是单词 a
的子集。 例如,“wrr” 是 “warrior” 的子集,但不是 “world” 的子集。
如果对 B
中的每一个单词 b
,b
都是 a
的子集,那么我们称 A
中的单词 a
是通用的。
你可以按任意顺序以列表形式返回 A
中所有的通用单词。
输入:A = ["amazon","apple","facebook","google","leetcode"], B = ["e","o"]
输出:["facebook","google","leetcode"]
输入:A = ["amazon","apple","facebook","google","leetcode"], B = ["l","e"]
输出:["apple","google","leetcode"]
输入:A = ["amazon","apple","facebook","google","leetcode"], B = ["e","oo"]
输出:["facebook","google"]
输入:A = ["amazon","apple","facebook","google","leetcode"], B = ["lo","eo"]
输出:["google","leetcode"]
输入:A = ["amazon","apple","facebook","google","leetcode"], B = ["ec","oc","ceo"]
输出:["facebook","leetcode"]
本题要求 对 B 中的每一个单词 b,b 都是 a 的子集。那么b中某一个字母出现几次,在a中也至少要有几次。对于多个b,某一单词出现的次数取最多的一次。
对于所有的b,采用一个哈希数组Bhash
统计每个字母出现的次数。对单个b,通过哈希数组bhash
统计在这个单词中每个字母出现的次数。在统计完后与总数组Bhash
进行比对,保留较大的值。
当所有b遍历完后获得最终的Bhash
,与每一个a的哈希数组进行比对即可。
class Solution:
def wordSubsets(self, A, B):
"""
:type A: List[str]
:type B: List[str]
:rtype: List[str]
"""
Bhash = {}
for str in B:
bhash = {}
for s in str:
if not s in bhash:
bhash[s] = 1
else: bhash[s] +=1
for i in bhash:
if not i in Bhash:
Bhash[i] = bhash[i]
else : Bhash[i] = max(Bhash[i],bhash[i])
res = []
for str in A:
ahash = {}
flag = 1
for s in str:
if not s in ahash:
ahash[s] = 1
else: ahash[s] +=1
for i in Bhash:
if not i in ahash:
flag = 0
break
elif ahash[i] < Bhash[i]:
flag = 0
break
if flag == 0:
continue
else :
res.append(str)
return res