思路
用哈希表统计words1和words2中各个字符串的出现次数,次数皆为1的字符串符合题意
解题方法
//用于存储words1中各个字符串的出现次数
HashMap<String,Integer> hashMap1=new HashMap<>();
//用于存储words2中各个字符串的出现次数
HashMap<String,Integer> hashMap2=new HashMap<>();
//如果words1中某个字符串出现一次且在words2中也出现一次,则ans++
if(hashMap1.getOrDefault(words1[i],-1)==1&&hashMap2.getOrDefault(words1[i],-1)==1) ans++;
时间复杂度,: O(n)
空间复杂度,: O(n)
Code
public static int countWords(String[] words1, String[] words2) {int ans=0;HashMap<String,Integer> hashMap1=new HashMap<>();//用于存储words1中各个字符串的出现次数HashMap<String,Integer> hashMap2=new HashMap<>();//用于存储words2中各个字符串的出现次数for(int i=0;i<words1.length;i++){ //记录words1中各个字符串的出现次数hashMap1.put(words1[i],hashMap1.getOrDefault(words1[i],0)+1);}for(int i=0;i<words2.length;i++){ //记录words2中各个字符串的出现次数hashMap2.put(words2[i],hashMap2.getOrDefault(words2[i],0)+1);}for(int i=0;i<words1.length;i++){ //如果words1中某个字符串出现一次且在words2中也出现一次,则ans++if(hashMap1.getOrDefault(words1[i],-1)==1&&hashMap2.getOrDefault(words1[i],-1)==1) ans++;}return ans; //返回结果}
注:hashMap1.get(words1[i])==1会报错,因为可能返回null
所以使用hashMap1.getOrDefault(words1[i],-1)==1
官方:
class Solution {public int countWords(String[] words1, String[] words2) {// 统计字符串出现频率Map<String, Integer> freq1 = new HashMap<>();Map<String, Integer> freq2 = new HashMap<>();for (String w : words1) {freq1.put(w, freq1.getOrDefault(w, 0) + 1);}for (String w : words2) {freq2.put(w, freq2.getOrDefault(w, 0) + 1);}// 遍历 words1 出现的字符并判断是否满足要求int res = 0;for (String w : freq1.keySet()) {if (freq1.get(w) == 1 && freq2.getOrDefault(w, 0) == 1) {res++;}}return res;}
}作者:力扣官方题解