916: Word-Subsets
Medium
table of contents
This question speaks to me like a Hash Map question.
My algorithm simply checks each word in words2
and generates an alphabet
array counting the
maximum number of each letter (of the alphabet) present
in any word of words2
. Then, you simply iterate through
words1
and check for universal strings, by
checking all the letter counts in words1[i]
is
greater than or equal to the letter counts in
alphabet
.
code
class Solution {
public:
<string> wordSubsets(vector<string>& words1, vector<string>& words2) {
vectorint alphabet[26] = {0};
int counter = 0;
for (string word : words2) {
int temp_alphabet[26] = {0};
for (char c : word) {
++temp_alphabet[c-'a'];
}
for (int i = 0; i < 26; ++i) {
[i] = max(alphabet[i], temp_alphabet[i]);
alphabet}
}
<string> ans;
vectorbool isUniversal;
for (string word : words1) {
int temp_alphabet[26] = {0};
for (char c : word) {
++temp_alphabet[c-'a'];
}
= true;
isUniversal for (int i = 0; i < 26; ++i) {
if (temp_alphabet[i] < alphabet[i]) {
= false;
isUniversal break;
}
}
if (isUniversal == true) {
.push_back(word);
ans}
}
return ans;
}
};