Skip to content

Commit 2d0a0ac

Browse files
authored
Merge pull request #42 from cp-sapienza/string_periods
String periods
2 parents 1529696 + af05ab6 commit 2d0a0ac

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

content/strings.tex

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,17 @@ \subsection{Z Function}
2424
\begin{flushleft}
2525
$z[i] = $ length of the longest substring starting at i that is a prefix of s \\
2626
$z[i] = $ max len s.t. $s[0..len-1] == s[i..i+len-1]$, $z[0] = 0$
27-
2827
\end{flushleft}
2928
\snippet{source/z_func.h}
3029

30+
\subsection{Periods}
31+
\bigo{N}
32+
33+
$k \leq N$ is a period of a string $s$ iff $\forall i, s[i] = s[i\%k]$. \\
34+
Note this means that 2 is a valid period of "aba"
35+
(uncomment the line if this is not wanted)
36+
\snippet{source/periods.h}
37+
3138
\subsection{KMP}
3239
\bigo{N} construction, \bigo{N+M} search with \bigo{|pat|} space.
3340

source/periods.h

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#pragma once
2+
#include "common.h"
3+
#include "z_func.h"
4+
5+
vi periods(string s) {
6+
vi z = z_function(s), p;
7+
int n = ssize(z);
8+
for(int i = 1; i < n; i++) {
9+
// if(n%i == 0) // uncomment for no trailing subperiods
10+
if(z[i]+i == n)
11+
p.push_back(i);
12+
}
13+
p.push_back(n);
14+
return p;
15+
}

0 commit comments

Comments
 (0)