[LeetCode] 2085. Count Common Words With One Occurrence

发布时间 2024-01-12 11:49:46作者: CNoodle

Given two string arrays words1 and words2, return the number of strings that appear exactly once in each of the two arrays.

Example 1:
Input: words1 = ["leetcode","is","amazing","as","is"], words2 = ["amazing","leetcode","is"]
Output: 2
Explanation:

  • "leetcode" appears exactly once in each of the two arrays. We count this string.
  • "amazing" appears exactly once in each of the two arrays. We count this string.
  • "is" appears in each of the two arrays, but there are 2 occurrences of it in words1. We do not count this string.
  • "as" appears once in words1, but does not appear in words2. We do not count this string.
    Thus, there are 2 strings that appear exactly once in each of the two arrays.

Example 2:
Input: words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"]
Output: 0
Explanation: There are no strings that appear in each of the two arrays.

Example 3:
Input: words1 = ["a","ab"], words2 = ["a","a","a","ab"]
Output: 1
Explanation: The only string that appears exactly once in each of the two arrays is "ab".

Constraints:
1 <= words1.length, words2.length <= 1000
1 <= words1[i].length, words2[j].length <= 30
words1[i] and words2[j] consists only of lowercase English letters.

统计出现过一次的公共字符串。

给你两个字符串数组 words1 和 words2 ,请你返回在两个字符串数组中 都恰好出现一次 的字符串的数目。

思路

用两个 hashmap map1 和 map2 分别记录 words1 和 words2 中每个不同单词的出现次数。遍历 map1 中的 keySet,如果 keySet 中的单词在 words1 和 words2 中均只出现一次,则这是一个符合题意的公共字符串。

复杂度

时间O(n)
空间O(n)

代码

Java实现

class Solution {
    public int countWords(String[] words1, String[] words2) {
        HashMap<String, Integer> map1 = new HashMap<>();
        for (String word : words1) {
            map1.put(word, map1.getOrDefault(word, 0) + 1);
        }

        HashMap<String, Integer> map2 = new HashMap<>();
        for (String word : words2) {
            map2.put(word, map2.getOrDefault(word, 0) + 1);
        }

        int count = 0;
        for (String word : map1.keySet()) {
            int val = map1.get(word);
            if (val == 1 && map2.containsKey(word) && map2.get(word) == 1) {
                count++;
            }
        }
        return count;
    }
}