We often encounter a situation that matches two strings to see if the Strpar contains str substrings, and if so, returns the substring's position in the parent string strpar, or False if it does not exist.
It is clear that we can solve the problem by brute force solution. That is, the first character and substring are compared from strpar, if successful, return to the first 0, if not successful, and then the second character began to compare, such a time complexity of O (m*n). As you can see, this complexity is quite high, then do we have a degree of complexity will be reduced? Obviously, there is a kind of called KMP algorithm which can greatly reduce the complexity O (m+n). The algorithm avoids a lot of hard work through the way of memory.
Like the character ... p1,p2,p3.....p ', p ', p ' ...
Suppose P1,p2 and P ', p ' are the same, when we compare the P ' "' when the comparison fails, simply push the P3 to compare with the parent string, because the front of him is certainly the same. The parent string does not need to be regressed at the same time.
So how do we get back, how much?
This requires a memory array, such as ABAABCAC
Back to the column page: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/
void GetNext (const char* str,int next[]) {
int i=0,j=-1;
Next[i]=j;
ASSERT (str);
while (i< (int) strlen (str)) {
if j==-1| | Str[i]==str[j]) {
i++,j++;
next[i]=j;
}
else
j=next[j];
}
After the next array is obtained, it is compared by Strpar and Str. If the same is i++,j++, otherwise str goes back, that is, j=next[j];
int Index (const char* strpar,const char* str,int next[]) {
int i=-1,j=-1;
ASSERT (STRPAR&&STR);
int M=strlen (STRPAR), N=strlen (str);
while (i<m&&j<n) {
if (j==-1| | STRPAR[I]==STR[J])
i++,j++;
else
j=next[j];
}
if (J==strlen (str)) return
i-j;
else
return-1;
}