Advertisement
Guest User

Untitled

a guest
Sep 15th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. #include <iostream> // std::ios, std::cin, std::cout
  2. #include <algorithm> // std::min
  3. #include <cstddef> // std::size_t
  4. #include <string> // std::string
  5. #include <vector> // std::vector
  6.  
  7. std::string DIVIDER = "#";
  8.  
  9. void computeFunction (const std::string &pattern, const std::string &source,
  10. std::vector<std::size_t> &function_values) {
  11.  
  12. std::string text = pattern + DIVIDER + source;
  13. std::size_t text_size = text.size();
  14. std::size_t left = 0, right = 0;
  15. for (std::size_t i = 1; i < text_size; ++i) {
  16.  
  17. if (i <= right) {
  18. function_values[i] = std::min(right - i + 1, function_values[i - left]);
  19. }
  20. while (i + function_values[i] < text_size && text[function_values[i]] == text[i + function_values[i]]) {
  21. ++function_values[i];
  22. }
  23. if (i + function_values[i] - 1 > right) {
  24. left = i;
  25. right = i + function_values[i] - 1;
  26. }
  27. }
  28. }
  29.  
  30. void computeMatchings (const std::string &pattern, const std::string &source,
  31. const std::vector<std::size_t> &function_values, std::vector<std::size_t> &matchings) {
  32.  
  33. for (std::size_t i = 0; i < function_values.size(); ++i) {
  34.  
  35. if (function_values[i] == pattern.size()) {
  36. matchings.emplace_back(i - pattern.size() - 1);
  37. }
  38. }
  39. }
  40.  
  41. void functor (const std::string &pattern, const std::string &source, std::vector<std::size_t> &matchings) {
  42.  
  43. std::size_t text_size = pattern.size() + DIVIDER.size() + source.size();
  44. std::vector<std::size_t> function_values(text_size, 0);
  45. computeFunction(pattern, source, function_values);
  46. matchings.clear();
  47. computeMatchings(pattern, source, function_values, matchings);
  48. }
  49.  
  50. int main () {
  51.  
  52. std::string pattern;
  53. std::string source;
  54. std::cin >> pattern >> source;
  55.  
  56. std::vector<std::size_t> matchings;
  57. functor(pattern, source, matchings);
  58. for (auto position: matchings) {
  59. std::cout << position << " ";
  60. }
  61. return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement