Start by building a prefix array.
Loop through it in reverse and stop the first time you find something that's repeated in your string (that is, it has a str.count()>1
.
Now if the same substring exists right next to itself, you can return it as the word you're looking for, however you must take into consideration the 'appleappl'
example, where the proposed algorithm would return appl
. For that, when you find a substring that exists more than once in your string, you return as a result that substring plus whatever is between its next occurence, namely for 'appleappl'
you return 'appl' +'e' = 'apple'
. If no such strings are found, you return the whole word since there are no repetitions.
def repeat(s):
prefix_array=[]
for i in range(len(s)):
prefix_array.append(s[:i])
#see what it holds to give you a better picture
print prefix_array
#stop at 1st element to avoid checking for the ' ' char
for i in prefix_array[:1:-1]:
if s.count(i) > 1 :
#find where the next repetition starts
offset = s[len(i):].find(i)
return s[:len(i)+offset]
break
return s
print repeat(s)