From 4ab2897545d30b201e56bb636ee7461af0293d99 Mon Sep 17 00:00:00 2001 From: Antti H S Laaksonen Date: Mon, 17 Apr 2017 18:26:00 +0300 Subject: [PATCH] Add Z-algorithm implementation [closes #20] --- chapter26.tex | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/chapter26.tex b/chapter26.tex index 654dcf0..fe6d23a 100644 --- a/chapter26.tex +++ b/chapter26.tex @@ -1129,4 +1129,24 @@ in the string \texttt{HATTIVATTI}. The time complexity of the resulting algorithm is $O(n)$, because it suffices to construct -the Z-array and go through its values. \ No newline at end of file +the Z-array and go through its values. + +\subsubsection{Implementation} + +Here is a short implementation of the Z-algorithm +that returns a vector that corresponds to the Z-array. + +\begin{lstlisting} +vector z(string s) { + int n = s.size(); + vector z(n); + int x = 0, y = 0; + for (int i = 1; i < n; i++) { + z[i] = max(0,min(z[i-x],y-i+1)); + while (i+z[i] < n && s[z[i]] == s[i+z[i]]) { + x = i; y = i+z[i]; z[i]++; + } + } + return z; +} +\end{lstlisting} \ No newline at end of file