forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
54 lines (43 loc) · 1.18 KB
/
main.cpp
File metadata and controls
54 lines (43 loc) · 1.18 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
/// Source : https://leetcode.com/problems/word-subsets/description/
/// Author : liuyubobobo
/// Time : 2018-09-30
#include <iostream>
#include <vector>
using namespace std;
/// Reduce set B into a single word b
/// Time Complexity: O(A.size() + B.size())
/// Space Complexity: O(26)
class Solution {
public:
vector<string> wordSubsets(vector<string>& A, vector<string>& B) {
vector<int> b = getFreq(B[0]);
for(int i = 1; i < B.size(); i ++){
vector<int> tb = getFreq(B[i]);
for(int j = 0; j < 26; j ++)
b[j] = max(b[j], tb[j]);
}
vector<string> res;
for(const string& word: A){
vector<int> a = getFreq(word);
if(contains(a, b))
res.push_back(word);
}
return res;
}
private:
vector<int> getFreq(const string& word){
vector<int> freq(26, 0);
for(char c: word)
freq[c - 'a'] ++;
return freq;
}
bool contains(const vector<int>& a, const vector<int>& b){
for(int i = 0; i < 26; i ++)
if(a[i] < b[i])
return false;
return true;
}
};
int main() {
return 0;
}