Assuming that the STR length is Len and the repeating substring length is k, then if it is true that a string of multiple consecutive lengths of K is repeated to form STR, then when the next is obtained for STR, the continuous symmetry (the equal of the strings in the front and back of the two dashed boxes) will start from next[k+1]. Increment , until Next[len]=len-k, and (len-k)%k==0, indicating an integral number of K
Always ask for Next[len] instead of next[len-1], because next[len-1] simply represents the inner symmetry of the first len-1 letters, without taking into account the last letter that str[len-1]
So the solution is very simple: first the next array of STR, always find Next[len], and then see if Next[len] is not 0 and divisible by K (K=len-next[len])
public class Solution {
public bool RepeatedSubstringPattern(string str) {
int length = str.Length;
int[] next = new int[length+1];//length+1 求最大公共元素长度数组
next[0] = -1;
int j = 0;
int k = -1;
while (j < length) {
if (k == -1 || str[j] == str[k]) {
++j;
++k;
next[j] = k;
} else {
k = next[k];
}
}
return [ length ] != 0 && next [ Span class= "PLN" >length ] % Span class= "PLN" > ( length - Span class= "PLN" > next [ length ) == 0 Span class= "pun";
}
}
From for notes (Wiz)
459. (KMP) asks if a string is composed of patterns repeating repeated Substring pattern