LeetCode2085. Count Common Words With One Occurrence

文章目录

一、题目

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.

二、题解

cpp 复制代码
class Solution {
public:
    int countWords(vector<string>& words1, vector<string>& words2) {
        unordered_map<string,int> map1;
        unordered_map<string,int> map2;
        for(auto w1:words1){
            map1[w1]++;
        }
        for(auto w2:words2){
            map2[w2]++;
        }
        int res = 0;
        for(auto w1:words1){
            if(map1[w1] == 1 && map2[w1] == 1) res++;
        }
        return res;
    }
};
相关推荐
清华都得不到的好学生39 分钟前
数据结构->1.稀疏数组,2.数组队列(没有取模),3.环形队列
java·开发语言·数据结构
SilentSlot40 分钟前
【数据结构】Hash
数据结构·算法·哈希算法
是娇娇公主~1 小时前
Lambda表达式详解
数据结构·c++
leaves falling1 小时前
C++ string 类:从入门到模拟实现
开发语言·c++
样例过了就是过了2 小时前
LeetCode热题100 柱状图中最大的矩形
数据结构·c++·算法·leetcode
wsoz2 小时前
Leetcode哈希-day1
算法·leetcode·哈希算法
阿Y加油吧2 小时前
LeetCode 二叉搜索树双神题通关!有序数组转平衡 BST + 验证 BST,小白递归一把梭
java·算法·leetcode
BlockChain8882 小时前
区块链的组件:从数据结构到去中心化共识
数据结构·去中心化·区块链
liuyao_xianhui3 小时前
优选算法_最小基因变化_bfs_C++
java·开发语言·数据结构·c++·算法·哈希算法·宽度优先
jimy13 小时前
C语言实现-----面向对象编程
c语言·数据结构