Merge branch '11_permutations_in_string'

This commit is contained in:
Manish 2023-03-10 21:07:45 +11:00
commit 73dc9e2272
2 changed files with 43 additions and 1 deletions

View File

@ -0,0 +1,40 @@
/* Problem: https://leetcode.com/problems/permutation-in-string/ */
#include <iostream>
#include <unordered_map>
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<char, std::size_t> 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';
}

View File

@ -26,3 +26,5 @@ 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(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) add_executable(11_letter_case_permutation 11_letter_case_permutation.cpp)
add_executable(11_permutations_in_string 11_permutations_in_string.cpp)