Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream> // std::ios, std::cin, std::cout
- #include <algorithm> // std::min
- #include <cstddef> // std::size_t
- #include <string> // std::string
- #include <vector> // std::vector
- std::string DIVIDER = "#";
- void computeFunction (const std::string &pattern, const std::string &source,
- std::vector<std::size_t> &function_values) {
- std::string text = pattern + DIVIDER + source;
- std::size_t text_size = text.size();
- std::size_t left = 0, right = 0;
- for (std::size_t i = 1; i < text_size; ++i) {
- if (i <= right) {
- function_values[i] = std::min(right - i + 1, function_values[i - left]);
- }
- while (i + function_values[i] < text_size && text[function_values[i]] == text[i + function_values[i]]) {
- ++function_values[i];
- }
- if (i + function_values[i] - 1 > right) {
- left = i;
- right = i + function_values[i] - 1;
- }
- }
- }
- void computeMatchings (const std::string &pattern, const std::string &source,
- const std::vector<std::size_t> &function_values, std::vector<std::size_t> &matchings) {
- for (std::size_t i = 0; i < function_values.size(); ++i) {
- if (function_values[i] == pattern.size()) {
- matchings.emplace_back(i - pattern.size() - 1);
- }
- }
- }
- void functor (const std::string &pattern, const std::string &source, std::vector<std::size_t> &matchings) {
- std::size_t text_size = pattern.size() + DIVIDER.size() + source.size();
- std::vector<std::size_t> function_values(text_size, 0);
- computeFunction(pattern, source, function_values);
- matchings.clear();
- computeMatchings(pattern, source, function_values, matchings);
- }
- int main () {
- std::string pattern;
- std::string source;
- std::cin >> pattern >> source;
- std::vector<std::size_t> matchings;
- functor(pattern, source, matchings);
- for (auto position: matchings) {
- std::cout << position << " ";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement