From 8901afccf4214b867f0a8303360388683da8bd5e Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Wed, 16 Nov 2022 10:58:20 +0800 Subject: [PATCH] s0030 --- ...string_with_concatenation_of_all_words.hpp | 15 +++++++++ ...string_with_concatenation_of_all_words.cpp | 33 +++++++++++++++++++ ...string_with_concatenation_of_all_words.cpp | 19 +++++++++++ 3 files changed, 67 insertions(+) create mode 100644 include/s0030_substring_with_concatenation_of_all_words.hpp create mode 100644 src/s0030_substring_with_concatenation_of_all_words.cpp create mode 100644 tests/s0030_substring_with_concatenation_of_all_words.cpp diff --git a/include/s0030_substring_with_concatenation_of_all_words.hpp b/include/s0030_substring_with_concatenation_of_all_words.hpp new file mode 100644 index 0000000..1e1cacc --- /dev/null +++ b/include/s0030_substring_with_concatenation_of_all_words.hpp @@ -0,0 +1,15 @@ +#ifndef S0030_SUBSTRING_WITH_CONCATENATION_OF_ALL_WORDS +#define S0030_SUBSTRING_WITH_CONCATENATION_OF_ALL_WORDS + +#include +#include +#include + +using namespace std; + +class Solution { + public: + vector findSubstring(string s, vector& words); +}; + +#endif diff --git a/src/s0030_substring_with_concatenation_of_all_words.cpp b/src/s0030_substring_with_concatenation_of_all_words.cpp new file mode 100644 index 0000000..5fc3584 --- /dev/null +++ b/src/s0030_substring_with_concatenation_of_all_words.cpp @@ -0,0 +1,33 @@ +#include "s0030_substring_with_concatenation_of_all_words.hpp" + +vector Solution::findSubstring(string s, vector& words) { + vector res; + int m = words.size(), n = words[0].size(), ls = s.size(); + for (int i = 0; i < n && i + m * n <= ls; ++i) { + unordered_map differ; + for (int j = 0; j < m; ++j) { + ++differ[s.substr(i + j * n, n)]; + } + for (string& word : words) { + if (--differ[word] == 0) { + differ.erase(word); + } + } + for (int start = i; start < ls - m * n + 1; start += n) { + if (start != i) { + string word = s.substr(start + (m - 1) * n, n); + if (++differ[word] == 0) { + differ.erase(word); + } + word = s.substr(start - n, n); + if (--differ[word] == 0) { + differ.erase(word); + } + } + if (differ.empty()) { + res.emplace_back(start); + } + } + } + return res; +} diff --git a/tests/s0030_substring_with_concatenation_of_all_words.cpp b/tests/s0030_substring_with_concatenation_of_all_words.cpp new file mode 100644 index 0000000..93bad95 --- /dev/null +++ b/tests/s0030_substring_with_concatenation_of_all_words.cpp @@ -0,0 +1,19 @@ +#include "s0030_substring_with_concatenation_of_all_words.hpp" + +#include + +TEST(Problem30, Case1) { + string s{"barfoothefoobarman"}; + vector words{"foo", "bar"}; + vector o{0, 9}; + Solution solution; + EXPECT_EQ(solution.findSubstring(s, words), o); +} + +TEST(Problem30, Case2) { + string s{"wordgoodgoodgoodbestword"}; + vector words{"word","good","best","word"}; + vector o{}; + Solution solution; + EXPECT_EQ(solution.findSubstring(s, words), o); +}