Input: words1 =["leetcode","is","amazing","as","is"], words2 =["amazing","leetcode","is"]Output: 2Explanation:
-"leetcode" appears exactly once in each of the two arrays. We count this string.-"amazing" appears exactly once in each of the two arrays. We count this string.-"is" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string.-"as" appears once in words1, but does not appear in words2. We do not count this string.Thus, there are 2 strings that appear exactly once in each of the two arrays.
If a word appears exactly once in both arrays, it is counted. We can use hash maps to count occurrences in each array, then count words that have a count of 1 in both.
classSolution {
public:int countWords(vector<string>& w1, vector<string>& w2) {
unordered_map<string, int> m1, m2;
for (auto& w : w1) m1[w]++;
for (auto& w : w2) m2[w]++;
int ans =0;
for (auto& [k, v] : m1) {
if (v ==1&& m2[k] ==1) ans++;
}
return ans;
}
};
classSolution {
publicintcountWords(String[] w1, String[] w2) {
Map<String, Integer> m1 =new HashMap<>(), m2 =new HashMap<>();
for (String w : w1) m1.put(w, m1.getOrDefault(w, 0) + 1);
for (String w : w2) m2.put(w, m2.getOrDefault(w, 0) + 1);
int ans = 0;
for (String k : m1.keySet()) {
if (m1.get(k) == 1 && m2.getOrDefault(k, 0) == 1) ans++;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funcountWords(w1: Array<String>, w2: Array<String>): Int {
val m1 = mutableMapOf<String, Int>()
val m2 = mutableMapOf<String, Int>()
for (w in w1) m1[w] = m1.getOrDefault(w, 0) + 1for (w in w2) m2[w] = m2.getOrDefault(w, 0) + 1var ans = 0for ((k, v) in m1) {
if (v ==1&& m2.getOrDefault(k, 0) ==1) ans++ }
return ans
}
}
1
2
3
4
5
6
classSolution:
defcountWords(self, w1: list[str], w2: list[str]) -> int:
from collections import Counter
c1 = Counter(w1)
c2 = Counter(w2)
return sum(1for k in c1 if c1[k] ==1and c2.get(k, 0) ==1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
use std::collections::HashMap;
impl Solution {
pubfncount_words(w1: Vec<String>, w2: Vec<String>) -> i32 {
letmut m1 = HashMap::new();
letmut m2 = HashMap::new();
for w in w1.iter() { *m1.entry(w).or_insert(0) +=1; }
for w in w2.iter() { *m2.entry(w).or_insert(0) +=1; }
letmut ans =0;
for (k, v) in m1.iter() {
if*v ==1&&*m2.get(k).unwrap_or(&0) ==1 { ans +=1; }
}
ans
}
}