916. Word Subsets(python+cpp)
阿新 • • 發佈:2018-11-13
題目:
We are given two arrays
A
andB
of words. Each word is a string of lowercase letters.
Now, say that wordb
is a subset of worda
if every letter inb
occurs ina
, including multiplicity. For example, “wrr” is a subset of “warrior”, but is not a subset of “world”.
Now say a word a fromA
is universal if for everyb
inB
,b
is a subset ofa
.
Return a list of all universal words in A. You can return the words in any order.
Example 1:Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["e","o"] Output: ["facebook","google","leetcode"]
Example 2:
Input: A = ["amazon","apple","facebook","google","leetcode"], B =["l","e"] Output: ["apple","google","leetcode"]
Example 3:
Input: A = ["amazon","apple","facebook","google","leetcode"], B =["e","oo"] Output: ["facebook","google"]
Example 4:
Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["lo","eo"] Output: ["google","leetcode"]
Example 5:
Input: A = ["amazon","apple","facebook","google","leetcode"], B = ["ec","oc","ceo"] Output: ["facebook","leetcode"]
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 inA[i]
are unique: there isn’ti != j
withA[i] == A[j]
.
解釋:
需要統計B中每個單詞中的每個字母在各自的單詞中所出現的最大的次數,構成一個屬於B的字典,只需拿這個字典和A中的每個a比較即可。
python用defaultdict速度比用Counter()速度快。
python程式碼:
from collections import Counter
class Solution:
def wordSubsets(self, A, B):
"""
:type A: List[str]
:type B: List[str]
:rtype: List[str]
"""
result=[]
count_B={}
for b in B:
count=Counter(b)
for key in count:
count_B[key]=max(count_B.get(key,0),count[key])
print (count_B)
for a in A:
count_a=Counter(a)
flag=True
for key in count_B:
if count_a.get(key,0)<count_B[key]:
flag=False
break
if flag:
result.append(a)
return result
python程式碼(使用defaultdict速度更快):
from collections import defaultdict
class Solution:
def wordSubsets(self, A, B):
"""
:type A: List[str]
:type B: List[str]
:rtype: List[str]
"""
result=[]
count_B=defaultdict(int)
for b in B:
count=defaultdict(int)
for letter in b:
count[letter]+=1
for key in count:
count_B[key]=max(count_B[key],count[key])
for a in A:
count_a=defaultdict(int)
for letter in a:
count_a[letter]+=1
flag=True
for key in count_B:
if count_a[key]<count_B[key]:
flag=False
break
if flag:
result.append(a)
return result
c++程式碼:
#include <map>
using namespace std;
class Solution {
public:
vector<string> wordSubsets(vector<string>& A, vector<string>& B) {
map<int,int>count_B;
for (auto b:B)
{
map<int,int>count_b;
for(auto letter:b)
{
count_b[letter]+=1;
}
for (auto item:count_b)
count_B[item.first]=max(item.second,count_B[item.first]);
}
vector<string> result;
for (auto a:A)
{
map<int,int>count_a;
for(auto letter:a)
count_a[letter]+=1;
bool flag=true;
for (auto item:count_B)
{
if (count_a[item.first]<item.second)
{
flag=false;
break;
}
}
if (flag)
result.push_back(a);
}
return result;
}
};
總結: