-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution.cpp
42 lines (39 loc) · 1.07 KB
/
solution.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
39
40
41
42
class Solution
{
public:
vector<string> wordSubsets(vector<string> &words1, vector<string> &words2)
{
vector<int> maxFreq(26, 0);
// Precompute the maximum frequency for each character in words2
for (const string &word : words2)
{
vector<int> freq(26, 0);
for (char c : word)
freq[c - 'a']++;
for (int i = 0; i < 26; ++i)
{
maxFreq[i] = max(maxFreq[i], freq[i]);
}
}
vector<string> result;
// Check each word in words1
for (const string &word : words1)
{
vector<int> freq(26, 0);
for (char c : word)
freq[c - 'a']++;
bool isUniversal = true;
for (int i = 0; i < 26; ++i)
{
if (freq[i] < maxFreq[i])
{
isUniversal = false;
break;
}
}
if (isUniversal)
result.push_back(word);
}
return result;
}
};