forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
word-subsets.cpp
38 lines (36 loc) · 934 Bytes
/
word-subsets.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Time: O(m + n)
// Space: O(1)
class Solution {
public:
vector<string> wordSubsets(vector<string>& A, vector<string>& B) {
vector<int> count(26);
for (const auto& b : B) {
const auto& tmp = counter(b);
for (int i = 0; i < 26; ++i) {
count[i] = max(count[i], tmp[i]);
}
}
vector<string> result;
for (const auto& a : A) {
const auto& tmp = counter(a);
int i = 0;
for (; i < 26; ++i) {
if (tmp[i] < count[i]) {
break;
}
}
if (i == 26) {
result.emplace_back(a);
}
}
return result;
}
private:
vector<int> counter(const string& word) {
vector<int> count(26);
for (const auto& c : word) {
++count[c - 'a'];
}
return count;
}
};