Skip to content

Commit a0027f2

Browse files
Update Z_Function_Efficient_Approach.cpp
1 parent 66c1cf7 commit a0027f2

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

Pattern_Matching/src/Z_Function_Efficient_Approach.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,15 @@
1+
/*For the sake of brevity, let's call segment matches those substrings that coincide with a prefix of s. For example, the value of the desired Z-function z[i] is the length of the segment match starting at position i (and that ends at position i+z[i]−1).
2+
To do this, we will keep the [l,r] indices of the rightmost segment match. That is, among all detected segments we will keep the one that ends rightmost. In a way, the index r can be seen as the "boundary" to which our string s has been scanned by the algorithm; everything beyond that point is not yet known.
3+
Then, if the current index (for which we have to compute the next value of the Z-function) is i, we have one of two options:
4+
i>r -- the current position is outside of what we have already processed.
5+
We will then compute z[i] with the trivial algorithm (that is, just comparing values one by one). Note that in the end, if z[i]>0, we'll have to update the indices of the rightmost segment, because it's guaranteed that the new r=i+z[i]−1 is better than the previous r.
6+
i≤r -- the current position is inside the current segment match [l,r].
7+
Then we can use the already calculated Z-values to "initialize" the value of z[i] to something (it sure is better than "starting from zero"), maybe even some big number.
8+
For this, we observe that the substrings s[l…r] and s[0…r−l] match. This means that as an initial approximation for z[i] we can take the value already computed for the corresponding segment s[0…r−l], and that is z[i−l].
9+
However, the value z[i−l] could be too large: when applied to position i it could exceed the index r. This is not allowed because we know nothing about the characters to the right of r: they may differ from those required.
10+
*/
11+
12+
113
#include <bits/stdc++.h>
214
using namespace std;
315
//fuction to calculate z array/vector.

0 commit comments

Comments
 (0)