@yangshun Your solution is correct but your reasoning is flawed. The problem is not when B is in A*(x+1). The problem that confuses most of us is why dont we check beyond x+1 when B is not in A*(x+1). I dont think your explanation is sufficient.

The reason why we only need to check x and x+1 is the following. A can be written as s1+s2. The only way B becomes a substring when A is repeated is if B itself is a repetition of substrings in A in some order. If B = [s1+s2]*k then we only need to check the lower bound x=len(B)\len(A). If B=[s2+s1]*x then repeating A x times is not enough since we cannot fully recover the last repetition; e.g. we will be missing s1. Therefore, we need to do it x+1 times. For example, A=s1s2 and B=s2s1s2s1. In this case, repeating A 2 times (lower bound) will become 2*A=s1s2s1s2. As you see, for us to recover B we need another A so we can append s1 to the last s2 above. Therefore, we only need to check x,x+1. If we still dont find B as a substring, then they dont follow the above form and hence the answer would be -1.