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

题目地址:力扣

题目难度:Easy

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


解法1:暴力搜索

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

class Solution {
public:
    int countWords(vector& words1, vector& 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& words1, vector& words2) {
        unordered_map 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)

你可能感兴趣的:(力扣刷题,leetcode,c++,哈希)