Skip to content

Instantly share code, notes, and snippets.

@prasoon2211
Created November 14, 2015 18:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prasoon2211/c37b18de408a85f24cc7 to your computer and use it in GitHub Desktop.
Save prasoon2211/c37b18de408a85f24cc7 to your computer and use it in GitHub Desktop.
Z algorithm in Python
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