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.

二、题解

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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值