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;
    }
};
相关推荐
小此方几秒前
从零开始手搓堆:核心操作实现 + 堆排序 + TopK 算法+ 向上调整 vs 向下调整建堆的时间复杂度严密证明!
开发语言·数据结构·算法
_OP_CHEN11 分钟前
从零开始的Qt开发指南:(五)Qt 常用控件之 QWidget(上):解锁 Qt 界面开发的核心基石
开发语言·c++·qt·前端开发·qwidget·gui开发·qt常用控件
sulikey2 小时前
深入讲解:什么是 RAII(资源获取即初始化)——原理、实现、面试常考点与实战示例
c++·面试·智能指针·raii·shared_ptr·auto_ptr·资源获取即初始化
艾莉丝努力练剑2 小时前
【Git:多人协作】Git多人协作实战:从同分支到多分支工作流
服务器·c++·人工智能·git·gitee·centos·项目管理
前端炒粉4 小时前
35.LRU 缓存
开发语言·javascript·数据结构·算法·缓存·js
断剑zou天涯6 小时前
【算法笔记】窗口内最大值或最小值的更新结构
java·笔记·算法
smj2302_796826526 小时前
解决leetcode第3753题范围内总波动值II
python·算法·leetcode
骑着猪去兜风.8 小时前
线段树(二)
数据结构·算法
fengfuyao9859 小时前
竞争性自适应重加权算法(CARS)的MATLAB实现
算法
散峰而望9 小时前
C++数组(二)(算法竞赛)
开发语言·c++·算法·github