Leetcode implement strstr ()

Source: Internet
Author: User

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;
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.