Alex_tz307

Z FUNCTION

Aug 16th, 2021
554
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.40 KB | None | 0 0
  1. vector<int> z_function(const string &s) { /// z[i] - cea mai lunga subsecventa ce incepe pe pozitia i si este prefix al intregului sir
  2.   int n = s.length();
  3.   vector<int> z(n);
  4.   for (int i = 0, l = 0, r = 0; i < n; ++i) {
  5.     if (i <= r)
  6.       z[i] = min(r - i + 1, z[i - l]);
  7.     while (i + z[i] < n && s[z[i]] == s[i + z[i]]) {
  8.       l = i;
  9.       r = i + z[i];
  10.       ++z[i];
  11.     }
  12.   }
  13.   return z;
  14. }
Advertisement
Add Comment
Please, Sign In to add comment