Leetcode 2085. Count Common Words With One Occurrence
Given two string arrays words1
and words2
, return the number of strings that appear exactly once in each of the two arrays.
words1
and words2
?0
)#include <iostream>
#include <vector>
#include <unordered_map>
#include <string>
using namespace std;
int countWords(vector<string>& words1, vector<string>& words2) {
unordered_map<string, int> count1, count2;
// Count occurrences in words1
for (const auto& word : words1) {
count1[word]++;
}
// Count occurrences in words2
for (const auto& word : words2) {
count2[word]++;
}
int result = 0;
// Iterate over the first map and check the conditions in the second map
for (const auto& entry : count1) {
if (entry.second == 1 && count2[entry.first] == 1) {
result++;
}
}
return result;
}
int main() {
vector<string> words1 = {"leetcode", "is", "amazing", "as", "is"};
vector<string> words2 = {"amazing", "leetcode", "is"};
cout << "Number of common words with one occurrence: " << countWords(words1, words2) << endl;
return 0;
}
words1
and words2
.words1
.words2
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?