Merge branch '11_permutations_in_string'
This commit is contained in:
commit
73dc9e2272
40
11_permutations_in_string.cpp
Normal file
40
11_permutations_in_string.cpp
Normal 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';
|
||||
}
|
@ -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)
|
||||
add_executable(11_letter_case_permutation 11_letter_case_permutation.cpp)
|
||||
|
||||
add_executable(11_permutations_in_string 11_permutations_in_string.cpp)
|
Loading…
Reference in New Issue
Block a user