力扣2085统计出现过一次的公共字符串

题目来源

力扣2085统计出现过一次的公共字符串

题目概述

给你两个字符串数组 words1 和 words2 ,请你返回在两个字符串数组中 都恰好出现一次 的字符串的数目。

思路分析

思路一. 可以使用两个map分别存储两个字符串数组中所有字符串出现的数量,最后统计两个map中value均为1的字符串。

思路二. 使用一个map统计words1的字符,遍历words2,如果遍历到的字符串在words1中出现的次数为1则打上标记,如果已经被打上标记,从map删除这个字符串,最后统计被打上标记的字符串个数。

代码实现

java实现

class Solution {
    public int countWords(String[] words1, String[] words2) {
        Map<String,Integer> map = new HashMap<>();
        for (String str : words1) {
            map.put(str, map.getOrDefault(str, 0) + 1);
        }
        int count = 0;
        for (String str : words2) {
            Integer word1Count = map.get(str);
            if (word1Count == null) {
                continue;
            }
			// 打上标记,计数加一
            if (word1Count == 1) {
                map.put(str, -1);
                count++;
            }
			// 删除字符串,计数减一
            if(word1Count == -1) {
                map.remove(str);
                count--;
            }
        }
        return count;
    }
}

c++实现

class Solution {
public:
    int countWords(vector<string>& words1, vector<string>& words2) {
        unordered_map<string, int> map;
        for (string str : words1) {
            map[str]++;
        }
        int count = 0;
        for (string str : words2) {
			// 打上标记,计数加一
            if (map[str] == 1) {
                map[str] = -1;
                count++;
				// 删除标记,计数减一
            }else if (map[str] == -1) {
                map[str]--;
                count--;
            }
        }
        return count;
    }
};
  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值