ZFunction.cpp 877 B

12345678910111213141516171819202122232425262728293031323334353637
  1. const int maxn = 1000;
  2. /*
  3. Given a string S of length n, the Z Algorithm produces an array Z
  4. where Z[i] is the length of the longest substring starting from S[i] which is also a prefix of S
  5. i.e. the maximum k such that S[j][i+j] for all 0 <= j<k. Note that Z[i]=0 means that S[0]!=S[i].
  6. O(n)
  7. */
  8. string s;
  9. int n;
  10. int z[maxn];
  11. void z_function() {
  12. z[0] = 1;
  13. int L = 0, R = 0;
  14. for (int i = 1; i < n; i++) {
  15. if (i > R) {
  16. L = R = i;
  17. while (R < n && s[R-L] == s[R]) R++;
  18. z[i] = R - L; R--;
  19. } else {
  20. int k = i - L;
  21. if (z[k] < R-i+1) z[i] = z[k];
  22. else {
  23. L = i;
  24. while (R < n && s[R-L] == s[R]) R++;
  25. z[i] = R-L; R--;
  26. }
  27. }
  28. }
  29. }
  30. void test() {
  31. memset(z, 0, sizeof(z));
  32. s = "abcabcabcabc";
  33. n = s.length();
  34. z_function();
  35. for (int i = 0; i < n; i++)
  36. cout << i << " " << s[i] << " " << z[i] << endl;
  37. }