LeetCode 2085. 统计出现过一次的公共字符串(C++)

题目地址:力扣

题目难度:Easy

涉及知识点:遍历、哈希表、STL方法


解法1:暴力搜索

思路:对于word1中的每一个字符串,判断其在word1中是否只出现了一次,而且也在word2中也恰好出现一次,若满足条件,计数器加1。这种方法不需要额外的空间,但是耗时很高。

class Solution {
public:
    int countWords(vector<string>& words1, vector<string>& words2) {
        int cnt = 0;
        for (int i = 0; i < words1.size(); ++i)
        // 在word1中只出现一次,且在word2中也只出现一次
        if (count(words1.begin(), words1.end(), words1[i]) == 1 
            && count(words2.begin(), words2.end(), words1[i]) == 1)
            ++cnt;
        return cnt;
    }
};

Accepted

  • 60/60 cases passed (96 ms)
  • Your runtime beats 6.53 % of cpp submissions
  • Your memory usage beats 99.59 % of cpp submissions (13.7 MB)

解法2:哈希表遍历

思路:我们可以遍历两个数组,以哈希表来存储其中出现的元素,若出现一次则为true,若出现多余一次则为false。最后再遍历一遍哈希表即可

class Solution {
public:
    int countWords(vector<string>& words1, vector<string>& words2) {
        unordered_map<string, bool> word1_map, word2_map;
        int cnt = 0;
        // 对两个数组遍历,若第一次访问元素则置为true,若第二次及以上访问置为false
        for (int i = 0; i < words1.size(); ++i)
            word1_map[words1[i]] = word1_map.find(words1[i]) == word1_map.end();
        for (int i = 0; i < words2.size(); ++i)
            word2_map[words2[i]] = word2_map.find(words2[i]) == word2_map.end();

        // 遍历哈希表
        for (auto i : word1_map)
        {
            // 若满足第一个数组中出现一次且第二个数组中出现一次,计数器加一
            if (i.second && (word2_map.find(i.first) != word2_map.end()) 
                && word2_map[i.first])
                ++cnt;
        }
        return cnt;
    }
};

Accepted

  • 60/60 cases passed (24 ms)
  • Your runtime beats 91.84 % of cpp submissions
  • Your memory usage beats 67.34 % of cpp submissions (17.6 MB)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值