题目来源:https://leetcode.com/contest/weekly-contest-104/problems/word-subsets/
问题描述
916. Word Subsets
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:
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 in
A[i]
are unique: there isn'ti != j
withA[i] == A[j]
.
------------------------------------------------------------
题意
给定字符串集合A和集合B,定义字符串b是字符串a的”subset”当且仅当b中字母出现次数小于等于a中对应字母出现的次数。对于A中的每个字符串,判断B中所有字符串是不是都是它的”subset”.
------------------------------------------------------------
思路
这次周赛的题目好多都是用map做的。用map记录B中各个字符串中每个字符出现的次数,再用一个map求这些map的并。然后再用map记录A中各个字符串每个字符出现的次数,与前面求并的map作比较即可。
------------------------------------------------------------
代码
class Solution {
public:
map<char, int> mp;
void init(vector<string> &B)
{
int i, j, len, lB = B.size();
map<char, int> bp;
map<char, int>::iterator it;
string b;
for (i=0; i<lB; i++)
{
b = B.at(i);
len = b.size();
bp.clear();
for (j=0; j<len; j++)
{
bp[b[j]]++;
}
for (it=bp.begin(); it!=bp.end(); it++)
{
if (mp[it->first] < it->second)
{
mp[it->first] = it->second;
}
}
}
}
vector<string> wordSubsets(vector<string>& A, vector<string>& B) {
init(B);
int i, j, len, lA = A.size(), lB = B.size();
string a;
map<char, int> ap, bp;
map<char, int>::iterator it;
bool is_ans = true;
vector<string> ans;
for (i=0; i<lA; i++)
{
is_ans = true;
a = A[i];
len = a.size();
ap.clear();
for (j=0; j<len; j++)
{
ap[a[j]]++;
}
for (it=mp.begin(); it!=mp.end(); it++)
{
if (ap[it->first] < it->second)
{
is_ans = false;
break;
}
}
if (is_ans)
{
ans.push_back(a);
}
}
return ans;
}
};