Skip to content

Commit

Permalink
Merge pull request #42 from cp-sapienza/string_periods
Browse files Browse the repository at this point in the history
String periods
  • Loading branch information
podd0 authored Jan 15, 2024
2 parents 1529696 + af05ab6 commit 2d0a0ac
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
9 changes: 8 additions & 1 deletion content/strings.tex
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,17 @@ \subsection{Z Function}
\begin{flushleft}
$z[i] = $ length of the longest substring starting at i that is a prefix of s \\
$z[i] = $ max len s.t. $s[0..len-1] == s[i..i+len-1]$, $z[0] = 0$

\end{flushleft}
\snippet{source/z_func.h}

\subsection{Periods}
\bigo{N}

$k \leq N$ is a period of a string $s$ iff $\forall i, s[i] = s[i\%k]$. \\
Note this means that 2 is a valid period of "aba"
(uncomment the line if this is not wanted)
\snippet{source/periods.h}

\subsection{KMP}
\bigo{N} construction, \bigo{N+M} search with \bigo{|pat|} space.

Expand Down
15 changes: 15 additions & 0 deletions source/periods.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#pragma once
#include "common.h"
#include "z_func.h"

vi periods(string s) {
vi z = z_function(s), p;
int n = ssize(z);
for(int i = 1; i < n; i++) {
// if(n%i == 0) // uncomment for no trailing subperiods
if(z[i]+i == n)
p.push_back(i);
}
p.push_back(n);
return p;
}

0 comments on commit 2d0a0ac

Please sign in to comment.