KMP
and Z
algorithms are well known algorithms for string searching,
KMP
algorithm deals with finding the patterns through a KMP f
I think this will do it.
def Z(lps):
# First assume that we always need to restart when we find a mismatch.
Z = [0] * len(lps)
# Step through adjacent pairs.
itr = enumerate(zip(lps, lps[1:]), start=1)
for i, (prev, cur) in itr:
if cur <= prev: # suffix stopped growing
Z[i - prev] = prev # Mark this suffix at its beginning.
# Ending the string is also a way to stop growing the suffix.
if cur > 0: # if we were still growing a suffix
# At end of loop, cur is the new prev, and i+1 is the new i.
# (i == len(lps) - 1, cur == lps[-1])
Z[i+1 - cur] = cur
return Z
Samples:
Z([0,0,0,1,2]) #=> [0,0,0,2,0]
Z([0,0,1,2,1,2]) #=> [0,0,2,0,2,0]