Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a cycle/repeats in a string?

Tags:

java

I need to detect a cycle/sequence in a string and return the first occurrence. How should I go about doing it?

Example :

2 0 5 3 1 5 3 1 5 3 1

The first sequence to occur is 5 3 1.

There is no rules. The sequence can be half the string length, for example

5 3123 1231 231 31 231 41 452 3453 21 312312 5 3123 1231 231 31 231 41 452 3453 21 312312

The sequence is 5 3123 1231 231 31 231 41 452 3453 21 312312

like image 226
seesee Avatar asked Dec 27 '22 02:12

seesee


2 Answers

Have you studied Floyds cycle-finding algorithm? That may well help you if you want to find cycles. Very easy to implement as well.

like image 82
rossum Avatar answered Jan 07 '23 18:01

rossum


Clarification based on the comments: cycle means a sequence of digits which repeats immediately. So

1 1

would be a cycle

1 3 1

wouldn't because the potential cycle of 1s is interupted by 3

1 3 1 3

is a cycle (1 3).

So a basic algorithm could look like this.

  1. Iterate of the String.

  2. For each Digit find it next occurrence in the String. If nothing found continue with the next character.

  3. If a next occurrence is found compare the sequence from the current digit up to the following occurrence with the sequence of same length beginning at the next occurence. If they are the same you found a cycle. If not continue with the next occurence.

like image 27
Jens Schauder Avatar answered Jan 07 '23 18:01

Jens Schauder