The picture shows equivalent words drawn cyclically.
Problem 37: Cyclic Equivalence |
Two words are cyclically equivalent if one is a conjugate (rotation) of the other. Testing their equivalence appears in some string matching questions but also in graph algorithms, for example, for checking the isomorphism of directed labelled graphs, in which the test applies to graph cycles.
The following algorithm tests cyclic equivalence using the alphabet ordering.
\begin{algorithmic} \STATE $(x,i,y,j) \leftarrow (uu,0,vv,0)$ \WHILE{$i\lt n \mbox{ and } j\lt n$} \STATE $k \leftarrow 0$ \WHILE{$k\lt n \mbox{ and } x[i+k] = y[j+k]$} \STATE $k \leftarrow k+1$ \ENDWHILE \IF{$k=n$} \RETURN{\True} \ENDIF \IF{$x[i+k] \gt y[j+k]$} \STATE $i \leftarrow i+k+1$ \ELSE \STATE $j \leftarrow j+k+1$ \ENDIF \ENDWHILE \RETURN{\False} \end{algorithmic}
When the alphabet has no clear ordering, it is useful to have a solution based on simpler types of symbol comparisons.