What
Calculate the array z
where z[i]
= longest common prefix of s
and s[i:]
.
Idea
- use dynamic programming
- maintain the interval
[l, r]
where:s[l : r + 1] == s[:r - l + 1]
(s[l...r]
is a prefix ofs
)r
is as big as possible
- for each position
i
, use the interval[l, r]
to initializez[i]
:- if
l <= i <= r
thens[l : i] == s[:i - l + 1]
- because
s[l : r + 1] == s[:r - l + 1]
(defined above)
- because
- if
i > r
then keep as0
- if
- then try increase
z[i]
(expand the prefix starts ati
) using the naive approach. - update
[l, r]
with[i, i + z[i] - 1]
ifi + z[i] - 1 > r
- this keeps
i > l
and increaser
as newz[i]
is computed.
- this keeps
Implementation
Complexity
- Time:
r
is always increase at each iteration
- Space:
Misc
- This has a similar spirit to LSP - Longest Suffix which is also a prefix.
- Reference: Z-function - VNOI wiki