Given two string arrays words1
and words2
, return the number of strings that appear exactly once in each of the two arrays.
LeetCode Problem - 2085
class Solution {
public int countWords(String[] words1, String[] words2) {
// Variable to store the count of words appearing exactly once in both arrays
int result = 0;
// HashMap to store the frequency of words in words1
HashMap<String, Integer> hm1 = new HashMap<>();
// HashMap to store the frequency of words in words2
HashMap<String, Integer> hm2 = new HashMap<>();
// Count the frequency of words in words1
for (String str : words1) {
hm1.put(str, hm1.getOrDefault(str, 0) + 1);
}
// Count the frequency of words in words2
for (String str : words2) {
hm2.put(str, hm2.getOrDefault(str, 0) + 1);
}
// Iterate through each word in words1
for (String word : words1) {
// If the word appears exactly once in both words1 and words2, increment the result
if (hm1.get(word) == 1 && hm2.getOrDefault(word, 0) == 1) {
result++;
}
}
// Return the count of words appearing exactly once in both arrays
return result;
}
}