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;
    }
};
相关推荐
aramae2 分钟前
C++ -- STL -- vector
开发语言·c++·笔记·后端·visual studio
lifallen21 分钟前
Paimon 原子提交实现
java·大数据·数据结构·数据库·后端·算法
lixzest22 分钟前
C++ Lambda 表达式详解
服务器·开发语言·c++·算法
EndingCoder25 分钟前
搜索算法在前端的实践
前端·算法·性能优化·状态模式·搜索算法
丶小鱼丶29 分钟前
链表算法之【合并两个有序链表】
java·算法·链表
不吃洋葱.1 小时前
前缀和|差分
数据结构·算法
_Chipen1 小时前
C++基础问题
开发语言·c++
灿烂阳光g1 小时前
OpenGL 2. 着色器
c++·opengl
哦吼!3 小时前
数据结构—二叉树(二)
数据结构
AA陈超3 小时前
虚幻引擎UE5专用服务器游戏开发-20 添加基础能力类与连招能力
c++·游戏·ue5·游戏引擎·虚幻