1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| import java.util.*;
public class _2085统计出现过一次的公共字符串 {
public int countWords(String[] words1, String[] words2) { Map<String, Integer> map1 = new HashMap<>(); Map<String, Integer> 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); }
List<String> temp = new ArrayList<>(); map1.forEach((k, v) -> { if (v == 1 && map2.getOrDefault(k, 0) == 1) { temp.add(k); } }); String[] res = new String[temp.size()]; for (int i = 0; i < temp.size(); i++) { res[i] = temp.get(i); } return res.length; }
public int countWords_gov(String[] words1, String[] words2) { Map<String, Integer> map = new HashMap<>(); int result = 0; for (String s : words1) { map.put(s, map.getOrDefault(s, 0) + 1000); } for (String s : words2) { map.put(s, map.getOrDefault(s, 0) + 1); } for (Integer value : map.values()) { if (value == 1001) { result++; } } return result; }
public int countWords_option(String[] words1, String[] words2) { Map<String, Integer> cntMap = new HashMap<>(); for (String word : words1) { if (cntMap.containsKey(word)) { cntMap.put(word, 2); } else { cntMap.put(word, 1); } } int answer = 0; for (String word : words2) { int cnt = cntMap.getOrDefault(word, 0); if ((cnt & 1) == 0) { continue; } if (cnt == 1) { answer++; cntMap.put(word, 3); } else if (cnt == 3) { answer--; cntMap.put(word, 4); } } return answer; }
}
|