const int maxn = 1000; /* Given a string S of length n, the Z Algorithm produces an array Z where Z[i] is the length of the longest substring starting from S[i] which is also a prefix of S i.e. the maximum k such that S[j][i+j] for all 0 <= j R) { L = R = i; while (R < n && s[R-L] == s[R]) R++; z[i] = R - L; R--; } else { int k = i - L; if (z[k] < R-i+1) z[i] = z[k]; else { L = i; while (R < n && s[R-L] == s[R]) R++; z[i] = R-L; R--; } } } } void test() { memset(z, 0, sizeof(z)); s = "abcabcabcabc"; n = s.length(); z_function(); for (int i = 0; i < n; i++) cout << i << " " << s[i] << " " << z[i] << endl; }