KMP algorithm:
/** Obtain the next value of each mode in the KMP algorithm. Next [I] = J indicates Pattern [0 .. i] the position of the element after the longest prefix suffix is J. When matching fails, the value of the previous next function is obtained */
Void get_next (char * pattern, int * Next)
{
Int length = strlen (pattern); // The total length of the pattern.
Next [0] = 0; // The first position must be 0
Int J = 0; // start position of the match
For (INT I = 1; I <length; I ++) // obtain the values of other bits of next
{
// If some characters have been matched but cannot be matched at the moment, search back
While (j> 0 & pattern [I]! = Pattern [J])
{
J = next [J-1]; // If the J-bit match fails, match from position next [J-1]
// Next [J-1] indicates the element behind the longest prefix Suffix in pattern [0 .. J-1]
}
// If it can match, push down a position, indicating that after successful match on the position J, the next bit to be considered is J + 1.
If (pattern [J] = pattern [I])
J ++;
Next [I] = J;
}
}
Char * strstr (char * haystack, char * needle ){
If (haystack = NULL | needle = NULL)
Return NULL;
If (needle [0] = '\ 0 ')
Return haystack;
Int length1 = strlen (haystack );
Int lengh2 = strlen (needle );
Int * Next = new int [leng2];
Get_next (needle, next );
Int J = 0;
For (INT I = 0; I <length1; I ++)
{
// Jump to next [J-1] In position J,
// Next [J-1] stores the location of the element after the longest prefix Suffix in pattern [0 .. J-1]
While (j> 0 & haystack [I]! = Needle [J])
J = next [J-1];
// The match is successful, and J is moved back by one
If (haystack [I] = needle [J])
J ++;
// All matches. the start position is returned.
If (j = leng22)
Return haystack + i-length2 + 1;
}
// No. null is returned.
Return NULL;
}