Advertisement
pasholnahuy

ПОиск подстроки

Sep 28th, 2023
1,140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.88 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <tuple>
  5.  
  6. using namespace std;
  7.  
  8. vector<int> zfunc(const string& s){
  9.     vector<int> z(s.size());
  10.     int first = 0;
  11.     int last = 1;
  12.     for (int i = 1; i < s.size(); ++i){
  13.         if (i >= first && i < last && z[i - first] + i < last){
  14.             z[i] = z[i - first];
  15.         } else {
  16.             z[i] = max(0, last - i);
  17.             first = i;
  18.             while (s[i + z[i]] == s[z[i]] && i + z[i] < s.size()){
  19.                 ++z[i];
  20.             }
  21.             last = i + z[i];
  22.         }
  23.     }
  24.     return z;
  25. }
  26.  
  27. int main() {
  28.     string s1, s2;
  29.     cin >> s1 >> s2;
  30.     string s = s2 + "#" + s1;
  31.     vector<int> z = zfunc(s);
  32.     for (size_t i = s2.size() + 1; i < s.size(); ++i){
  33.         if (z[i] == s2.size()){
  34.             cout << i - s2.size() - 1 << " ";
  35.         }
  36.     }
  37.     return 0;
  38. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement