Skip to content

Commit 061431a

Browse files
committed
feat(word-subsets): solution for problem 0916
1 parent beaa36f commit 061431a

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

cpp/916.word-subsets.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
* @lc app=leetcode id=916 lang=cpp
3+
*
4+
* [916] Word Subsets
5+
*/
6+
7+
// @lc code=start
8+
class Solution
9+
{
10+
public:
11+
vector<string> wordSubsets(vector<string> &words1, vector<string> &words2)
12+
{
13+
14+
vector<string> result; // result vector
15+
vector<int> count(26, 0); // count vector
16+
17+
for (auto &word : words2) // for each word in words2
18+
{
19+
vector<int> temp(26, 0); // initialize a temporary vector to store the count of each letter in the word
20+
for (auto &c : word) // for each letter in the word
21+
{
22+
temp[c - 'a']++; // increment the count of the letter
23+
}
24+
for (int i = 0; i < 26; i++) // for each letter in the temporary vector
25+
{
26+
count[i] = max(count[i], temp[i]); // assign the maximum count of the letter to the count vector
27+
}
28+
}
29+
30+
for (auto &word : words1) // for each word in words1
31+
{
32+
vector<int> temp(26, 0); // initialize a temporary vector to store the count of each letter in the word
33+
for (auto &c : word) // for each letter in the word
34+
{
35+
temp[c - 'a']++; // increment the count of the letter
36+
}
37+
bool flag = true; // initialize a flag to indicate whether the word is a subset of the words2
38+
for (int i = 0; i < 26; i++) // for each letter in the temporary vector
39+
{
40+
if (temp[i] < count[i]) // if the count of the letter is less than the maximum count of the letter
41+
{
42+
flag = false; // the word is not a subset of the words2
43+
break;
44+
}
45+
}
46+
if (flag) // if the word is a subset of the words2
47+
{
48+
result.push_back(word); // add the word to the result vector
49+
}
50+
}
51+
52+
return result;
53+
}
54+
};
55+
// @lc code=end

0 commit comments

Comments
 (0)