Created
November 14, 2015 18:13
-
-
Save prasoon2211/c37b18de408a85f24cc7 to your computer and use it in GitHub Desktop.
Z algorithm in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def z_arr(s): | |
"""An advanced computation of Z-values of a string.""" | |
# From https://ivanyu.me/blog/2013/10/15/z-algorithm/ | |
Z = [0] * len(s) | |
Z[0] = len(s) | |
rt = 0 | |
lt = 0 | |
for k in range(1, len(s)): | |
if k > rt: | |
# If k is outside the current Z-box, do naive computation. | |
n = 0 | |
while n + k < len(s) and s[n] == s[n+k]: | |
n += 1 | |
Z[k] = n | |
if n > 0: | |
lt = k | |
rt = k+n-1 | |
else: | |
# If k is inside the current Z-box, consider two cases. | |
p = k - lt # Pair index. | |
right_part_len = rt - k + 1 | |
if Z[p] < right_part_len: | |
Z[k] = Z[p] | |
else: | |
i = rt + 1 | |
while i < len(s) and s[i] == s[i - k]: | |
i += 1 | |
Z[k] = i - k | |
lt = k | |
rt = i - 1 | |
return Z |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment