MCPcopy Create free account
hub / github.com/ShahjalalShohag/code-library / z_function

Function z_function

Strings/Z Algorithm.cpp:8–20  ·  view source on GitHub ↗

An element Z[i] of Z array stores length of the longest substring starting from str[i] which is also a prefix of str[0..n-1]. The first entry of Z array is meaning less as complete string is always prefix of itself. Here Z[0]=0.

Source from the content-addressed store, hash-verified

6// The first entry of Z array is meaning less as complete string is always prefix of itself.
7// Here Z[0]=0.
8vector<int> z_function(string s) {
9 int n = (int) s.length();
10 vector<int> z(n);
11 for (int i = 1, l = 0, r = 0; i < n; ++i) {
12 if (i <= r)
13 z[i] = min (r - i + 1, z[i - l]);
14 while (i + z[i] < n && s[z[i]] == s[i + z[i]])
15 ++z[i];
16 if (i + z[i] - 1 > r)
17 l = i, r = i + z[i] - 1;
18 }
19 return z;
20}
21int32_t main() {
22 string s;
23 cin >> s;

Callers 1

mainFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected