diff --git a/README.md b/README.md index 23f3742..a90b426 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,10 @@ C++标准库提供的数据结构实在是太多了,参考[C++标准库头文 ### 数组/队列/集合/映射 +- [统计出现过一次的公共字符串](src/array/count_common_words_with_one_occurrence.cpp) [数组, 哈希表, 字符串, 计数] + + - LeetCode 2085. 统计出现过一次的公共字符串 + - [回旋镖的数量](src/array/number_of_boomerangs.cpp) [数组, 哈希表, 数学] - LeetCode 447. 回旋镖的数量 diff --git a/images/array/count_common_words_with_one_occurrence.jpeg b/images/array/count_common_words_with_one_occurrence.jpeg new file mode 100644 index 0000000..060d63d Binary files /dev/null and b/images/array/count_common_words_with_one_occurrence.jpeg differ diff --git a/src/array/count_common_words_with_one_occurrence.cpp b/src/array/count_common_words_with_one_occurrence.cpp new file mode 100644 index 0000000..bca3f82 --- /dev/null +++ b/src/array/count_common_words_with_one_occurrence.cpp @@ -0,0 +1,26 @@ +// 统计出现过一次的公共字符串 +// https://leetcode.cn/problems/count-common-words-with-one-occurrence +// INLINE ../../images/array/count_common_words_with_one_occurrence.jpeg + +#include + +class Solution { +public: + int countWords(vector &words1, vector &words2) { + unordered_map map1, map2; + for (const string &w : words1) { + ++map1[w]; + } + for (const string &w : words2) { + ++map2[w]; + } + + int res = 0; + for (const auto &[w, cnt1] : map1) { + if (cnt1 == 1 && map2[w] == 1) { + ++res; + } + } + return res; + } +}; \ No newline at end of file diff --git a/test/array/count_common_words_with_one_occurrence_test.cpp b/test/array/count_common_words_with_one_occurrence_test.cpp new file mode 100644 index 0000000..7b92797 --- /dev/null +++ b/test/array/count_common_words_with_one_occurrence_test.cpp @@ -0,0 +1,32 @@ +#include + +TEST(统计出现过一次的公共字符串, countWords) { + Solution solution; + // 示例 1: + // 输入:words1 = ["leetcode","is","amazing","as","is"], words2 = + // ["amazing","leetcode","is"] 输出:2 解释: + // - "leetcode" 在两个数组中都恰好出现一次,计入答案。 + // - "amazing" 在两个数组中都恰好出现一次,计入答案。 + // - "is" 在两个数组中都出现过,但在 words1 中出现了 2 次,不计入答案。 + // - "as" 在 words1 中出现了一次,但是在 words2 中没有出现过,不计入答案。 + // 所以,有 2 个字符串在两个数组中都恰好出现了一次。 + vector words1 = {"leetcode", "is", "amazing", "as", "is"}; + vector words2 = {"amazing", "leetcode", "is"}; + EXPECT_EQ(solution.countWords(words1, words2), 2); + + // 示例 2: + // 输入:words1 = ["b","bb","bbb"], words2 = ["a","aa","aaa"] + // 输出:0 + // 解释:没有字符串在两个数组中都恰好出现一次。 + words1 = {"b", "bb", "bbb"}; + words2 = {"a", "aa", "aaa"}; + EXPECT_EQ(solution.countWords(words1, words2), 0); + + // 示例 3: + // 输入:words1 = ["a","ab"], words2 = ["a","a","a","ab"] + // 输出:1 + // 解释:唯一在两个数组中都出现一次的字符串是 "ab" 。 + words1 = {"a", "ab"}; + words2 = {"a", "a", "a", "ab"}; + EXPECT_EQ(solution.countWords(words1, words2), 1); +} diff --git a/test/lib/lib_test.cpp b/test/lib/lib_test.cpp index d966976..acb8b05 100644 --- a/test/lib/lib_test.cpp +++ b/test/lib/lib_test.cpp @@ -1,4 +1,4 @@ -// 执行编译时间:2024-01-11 11:49:55 +// 执行编译时间:2024-01-12 11:35:49 #include #include