Initial string S with length Len. Double the string (really we need S + half of S). Search for occurrence of initial string S in doubled string SS, beginning from 2nd position, ending at Len/2 + 1. If such occurence exists with position P, then S is periodic with period P - 1.
S = abbaabbaabba Len = 12
SS = abbaabbaabbaabbaabbaabba
Searching from 2nd to 7th position, S found at P=5, period = 4
S = abaabaabaabb
SS = abaabaabaabbabaabaabaabb
S doesn't occur in SS (except for 1 and L+1), no period exists
P.S. Note due to useful Venkatesh comment:
We need to add minimal possible periodic unit, it's length is L/2 for even-size strings, and maximum divisor of L for odd-size strings (if length is prime number, string cannot be periodic). Simple factorization methods have O(N^1/2) complexity, more complex - O(N^1/4), so sometimes it is worth to factorize length to avoid unnecessary comparison of long strings.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…