Advertisement
Guest User

Untitled

a guest
Dec 13th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <string>
  4. #include <vector>
  5.  
  6. int finder_value_z_function(const std::string & str, int & right, int & left, int index, int last_value_z_function) {
  7. int z_function = std::max(0, std::min(right - index + 1, last_value_z_function));
  8. while (index + z_function < str.length()
  9. && str[z_function] == str[index + z_function]) {
  10. ++z_function;
  11. }
  12. if (index + z_function - 1 > right) {
  13. left = index;
  14. right = index + z_function;
  15. }
  16. return z_function;
  17. }
  18.  
  19. std::vector<int> substring_search(const std::string & pattern, const std::string & text)
  20. {
  21. std::string str = pattern + '#' + text;
  22. int patternLen = pattern.length();
  23. std::vector<int> z_function(patternLen);
  24. std::vector<int> ans;
  25. z_function[0] = 0;
  26. for (int i = 1, left = 0, right = 0; i < str.length(); ++i) {
  27. if (i < patternLen) {
  28. z_function[i] = finder_value_z_function(str, right, left, i, z_function[i - left]);
  29. }
  30. else {
  31. int j = std::max(0, std::min(right - i + 1, z_function[i - left]));
  32. while (i + j - 1< str.length() && str[j] == str[i + j]) {
  33. ++j;
  34. }
  35. if (i + j > right) {
  36. left = i;
  37. right = i + j;
  38. }
  39. if (j == patternLen) {
  40. ans.push_back(i - patternLen - 1);
  41. }
  42. }
  43. }
  44. return ans;
  45. }
  46.  
  47. int main()
  48. {
  49. std::string patt, str;
  50. std::cin >> patt >> str;
  51. std::vector<int> answer = substring_search(patt, str);
  52. for (int i : answer) {
  53. std::cout << i << " ";
  54. }
  55. return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement