I'm working on a problem to find wholly repeated shortest substring of a given string, and if no match, return length of the string.
My major idea is learned from Juliana's answer here (Check if string is repetition of an unknown substring), I rewrite the algorithm in Python 2.7.
I think it should be O(n^2)
, but not confident I am correct, here is my thought -- since in the outer loop, it tries possibility of begin character to iterate with -- it is O(n)
external loop, and in the inner loop, it compares character one by one -- it is O(n)
internal comparison. So, overall time complexity is O(n^2)
? If I am not correct, please help to correct. If I am correct, please help to confirm. :)
Input and output example
catcatcat => 3
aaaaaa=>1
aaaaaba = > 7
My code,
def rorate_solution(word):
for i in range(1, len(word)//2 + 1):
j = i
k = 0
while k < len(word):
if word[j] != word[k]:
break
j+=1
if j == len(word):
j = 0
k+=1
else:
return i
return len(word)
if __name__ == "__main__":
print rorate_solution('catcatcat')
print rorate_solution('catcatcatdog')
print rorate_solution('abaaba')
print rorate_solution('aaaaab')
print rorate_solution('aaaaaa')