Problem
We are given two arrays A
and B
of words. Each word is a string of lowercase letters.
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"
.
Now say a word a
from A
is universal if for every b
in B
, b
is a subset of a
.
Return a list of all universal words in A
. You can return the words in any order.
Example 1:
1 | Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["e","o"] |
Example 2:
1 | Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["l","e"] |
Example 3:
1 | Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["e","oo"] |
Example 4:
1 | Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["lo","eo"] |
Example 5:
1 | Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["ec","oc","ceo"] |
Note:
1 <= A.length, B.length <= 10000
1 <= A[i].length, B[i].length <= 10
A[i]
andB[i]
consist only of lowercase letters.- All words in
A[i]
are unique: there isn’ti != j
withA[i] == A[j]
.
Analysis
题目给出A
和B
两个字符串数组,定义A
中的某个单词a
是universal如果所有在B
中出现的字母都在a
出现,包括出现的次数。因为这里有次数的要求,所以我们首先找到最低条件:在B中每个字符都需要出现多少次。例如B = ["facebook", leetcode"]
,那么它o
的最大出现次数就是2,来自于facebook
这个单词。
然后我们再对A
的单词逐个遍历,同样地计算出这个单词每个字母出现的次数,然后对比每个字母出现次数是否都大于等于B的最低要求,如果都满足,这个单词就是universal,加入到答案中;否则就检查下一个。
Solution
无
Code
1 | class Solution { |
Summary
这道题目的关键点在于找到判断universal的最低条件。因为每次都需要和B
中所有的单词比较,所以可以先把这个最低条件求出来,然后每次只需要和这个条件做比较即可。这道题目的分享到这里,感谢你的支持!