From 0225aaf204fb3aed83bbb3514a144545b0bcffbf Mon Sep 17 00:00:00 2001 From: Manish Date: Fri, 10 Mar 2023 21:07:04 +1100 Subject: [PATCH] Design Pattern 11 | Problem: Permutation in String --- 11_permutations_in_string.cpp | 40 +++++++++++++++++++++++++++++++++++ CMakeLists.txt | 4 +++- 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 11_permutations_in_string.cpp diff --git a/11_permutations_in_string.cpp b/11_permutations_in_string.cpp new file mode 100644 index 0000000..b218c61 --- /dev/null +++ b/11_permutations_in_string.cpp @@ -0,0 +1,40 @@ +/* Problem: https://leetcode.com/problems/permutation-in-string/ */ + +#include +#include + +bool solution(const std::string s1, const std::string s2) { + if (s1.length() > s2.length()) + return false; + std::size_t s1_len = s1.length(); + std::unordered_map s1_count, s2_substr_count; + for (const char c : s1) + s1_count[c]++; + for (auto c = s2.cbegin(), e = s2.cbegin() + s1.length(); c != e; c++) { + s2_substr_count[*c]++; + } + for (std::size_t i = s1_len, upto = s2.length(); i < upto; i++) { + bool match_found = true; + for (auto const [character, count] : s1_count) { + if (s2_substr_count[character] != count) { + match_found = false; + break; + } + } + if (match_found) + return true; + s2_substr_count[s2[i - s1_len]]--; + s2_substr_count[s2[i]]++; + } + for (auto const [character, count] : s1_count) { + if (s2_substr_count[character] != count) + return false; + } + return true; +} + +int main() { + std::cout << solution("ab", "eidbaooo") << '\n' + << solution("ab", "eidboaoo") << '\n' + << solution("dinitrophenylhydrazine", "dimethylhydrazine") << '\n'; +} \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt index 80f6d29..eaa1c32 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -25,4 +25,6 @@ add_executable(9_path_sum_iii 9_path_sum_iii.cpp) add_executable(10_find_the_median_of_a_number_stream 10_find_the_median_of_a_number_stream.cpp) -add_executable(11_letter_case_permutation 11_letter_case_permutation.cpp) \ No newline at end of file +add_executable(11_letter_case_permutation 11_letter_case_permutation.cpp) + +add_executable(11_permutations_in_string 11_permutations_in_string.cpp) \ No newline at end of file