赞
踩
给你两个字符串数组 words1 和 words2 ,请你返回在两个字符串数组中 都恰好出现一次 的字符串的数目。
words1 = [“leetcode”,“is”,“amazing”,“as”,“is”], words2 = [“amazing”,“leetcode”,“is”]
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; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。