Proposition: Design algorithm, in string s, starting at the POS position to find the first starting position of the same substring as the target string T.
KMP algorithm implementation: The first step is to preprocess the target string T to find out where each character in T is moved to when the character in the source string s is unequal. The method is based on the following formula
next[0]=-1;
next[j]=max{k|0<k<j&&"t0t1...t(k-1)"=="t(j-k)t(j-k+1)...t(j-1)"};
next[j]=0;
This formula can be proved as follows
First, assuming that the target string moves to K next time, what is the characteristic of this k position, all the characters before K (K, starting from 0) should be the same as the K characters before the I position in the source string s, namely:
"t0t1...t(k-1)"=="s(i-k)s(i-k+1)...s(i-1)"
Moreover, at this point, the K characters before the source string I position and the K character before the target string J position are the same, namely:
"t(j-k)t(j-k+1)...t(j-1)"=="s(i-k)s(i-k+1)...s(i-1)"
So get to the conclusion
"t0t1...t(k-1)"=="t(j-k)t(j-k+1)...t(j-1)"
The second step is to loop the source string and the target string, such as the next, this paragraph is not easy to say
while (S[i]!= ' && t[j]!= ')
{
if (j = = 1 | | s[i] = = T[j])//j==-1 indicates s[i] is different from t[0
{
i++;
j + +;
}
Else
{
j = Next[j];
}
}
if (t[j] = = ")
return i-j;
Else
return 0;