题目地址:
https://leetcode.com/problems/count-common-words-with-one-occurrence/
给定两个字符串数组 A A A和 B B B,求有多少个字符串在各自数字里只出现一次。
用两个哈希表计个数即可。代码如下:
import java.util.HashMap;
import java.util.Map;
public class Solution {
public int countWords(String[] words1, String[] words2) {
Map<String, Integer> map1 = new HashMap<>(), map2 = new HashMap<>();
for (String s : words1) {
map1.put(s, map1.getOrDefault(s, 0) + 1);
}
for (String s : words2) {
map2.put(s, map2.getOrDefault(s, 0) + 1);
}
int res = 0;
for (Map.Entry<String, Integer> entry : map1.entrySet()) {
String s = entry.getKey();
int cnt = entry.getValue();
if (cnt == 1 && map2.getOrDefault(s, 0) == 1) {
res++;
}
}
return res;
}
}
时空复杂度 O ( ( l A + l B ) l ) O((l_A+l_B)l) O((lA+lB)l), l l l为字符串最长长度。