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;
    }
};
相关推荐
一个小白120 分钟前
C++——list模拟实现
开发语言·c++
liuyuzhongcc29 分钟前
List 接口中的 sort 和 forEach 方法
java·数据结构·python·list
北_鱼32 分钟前
支持向量机(SVM):算法讲解与原理推导
算法·机器学习·支持向量机
程序员老舅35 分钟前
C++ Qt项目教程:WebServer网络测试工具
c++·qt·测试工具·webserver·qt项目·qt项目实战
靡不有初1111 小时前
CCF-CSP第18次认证第一题——报数【两个与string相关的函数的使用】
c++·学习·ccfcsp
计算机小白一个2 小时前
蓝桥杯 Java B 组之背包问题、最长递增子序列(LIS)
java·数据结构·蓝桥杯
MZWeiei2 小时前
PTA:运用顺序表实现多项式相加
算法
卑微的小鬼2 小时前
数据库使用B+树的原因
数据结构·b树
GISer_Jing2 小时前
Javascript排序算法(冒泡排序、快速排序、选择排序、堆排序、插入排序、希尔排序)详解
javascript·算法·排序算法
cookies_s_s2 小时前
Linux--进程(进程虚拟地址空间、页表、进程控制、实现简易shell)
linux·运维·服务器·数据结构·c++·算法·哈希算法