LC.P2085[统计出现过一次的公共字符串]

方法一:哈希表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int countWords(String[] words1, String[] words2) {
Map<String, Integer> map1 = new HashMap<>(), map2 = new HashMap<>();
for (String s : words1) map1.merge(s, 1, Integer::sum);
for (String s : words2) map2.merge(s, 1, Integer::sum);
int ans = 0;
for (Map.Entry<String, Integer> e : map1.entrySet()) {
if (e.getValue() == 1 && map2.getOrDefault(e.getKey(), 0) == 1) {
++ans;
}
}
return ans;
}
}
  • 时间复杂度:$O(n + m)$
  • 空间复杂度:$O(n + m)$