题目描述:
输入:
输出:
解释:
- “leetcode” 在两个数组中都恰好出现一次,计入答案。
- “amazing” 在两个数组中都恰好出现一次,计入答案。
- “is” 在两个数组中都出现过,但在 words1 中出现了 2 次,不计入答案。
- “as” 在 words1 中出现了一次,但是在 words2 中没有出现过,不计入答案。
所以,有 2 个字符串在两个数组中都恰好出现了一次。
代码实现:
public class Main{
public static void main(String[] args) {
String[] words1 = new String[]{"leetcode", "is", "amazing", "as", "is"};
String[] words2 = new String[]{"amazing", "leetcode", "is"};
System.out.println(countWords(words1, words2));//2
}
public static int countWords(String[] words1, String[] words2) {
//将两个字符串数组存入HashMap:key为字符串,value为出现次数
HashMap<String, Integer> hm1 = new HashMap<>();
HashMap<String, Integer> hm2 = new HashMap<>();
//计数器
int cnt = 0;
//统计数组1中的键值对
for (String value : words1) {
hm1.put(value, hm1.getOrDefault(value, 0) + 1);
}
//统计数组2中的键值对
for (String string : words2) {
hm2.put(string, hm2.getOrDefault(string, 0) + 1);
}
//判断两个map中公共仅出现一次字符串的次数
for (String s : words1) {
if (hm1.get(s) == 1 && hm2.getOrDefault(s, 0) == 1) {
cnt++;
}
}
return cnt;
}
}