Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- #include <iostream>
- #include <string>
- #include <vector>
- int finder_value_z_function(const std::string & str, int & right, int & left, int index, int last_value_z_function) {
- int z_function = std::max(0, std::min(right - index + 1, last_value_z_function));
- while (index + z_function < str.length()
- && str[z_function] == str[index + z_function]) {
- ++z_function;
- }
- if (index + z_function - 1 > right) {
- left = index;
- right = index + z_function;
- }
- return z_function;
- }
- std::vector<int> substring_search(const std::string & pattern, const std::string & text)
- {
- std::string str = pattern + '#' + text;
- int patternLen = pattern.length();
- std::vector<int> z_function(patternLen);
- std::vector<int> ans;
- z_function[0] = 0;
- for (int i = 1, left = 0, right = 0; i < str.length(); ++i) {
- if (i < patternLen) {
- z_function[i] = finder_value_z_function(str, right, left, i, z_function[i - left]);
- }
- else {
- int j = std::max(0, std::min(right - i + 1, z_function[i - left]));
- while (i + j - 1< str.length() && str[j] == str[i + j]) {
- ++j;
- }
- if (i + j > right) {
- left = i;
- right = i + j;
- }
- if (j == patternLen) {
- ans.push_back(i - patternLen - 1);
- }
- }
- }
- return ans;
- }
- int main()
- {
- std::string patt, str;
- std::cin >> patt >> str;
- std::vector<int> answer = substring_search(patt, str);
- for (int i : answer) {
- std::cout << i << " ";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement