- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathz-algorithm.py
More file actions
Latest commit
25 lines (19 loc) · 618 Bytes
/
Copy pathz-algorithm.py
File metadata and controls
25 lines (19 loc) · 618 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
r"""Z algorithm for linear-time prefix matching.
For each position $i$ in a string $s$, let $Z[i]$ be the length of the longest
prefix of $s$ matching the substring starting at $i$. The algorithm maintains
a rightmost matching interval $[l, r)$ and reuses it to avoid redundant
comparisons.
Runs in $O(n)$ time.
"""
defz_algorithm(s):
n=len(s)
Z= [0] *n
l=r=0
foriinrange(1, n):
ifi<r:
Z[i] =min(r-i, Z[i-l])
whilei+Z[i] <nands[Z[i]] ==s[i+Z[i]]:
Z[i] +=1
ifi+Z[i] >r:
l, r=i, i+Z[i]
returnZ