Leetcode: Implement strstr ()

Source: Internet
Author: User


Implement strstr ().

Returns a pointer to the first occurrence of needle in haystack, or null if

Needle is not part of haystack.


Solution:

The strstr () function belongs to the string. h header file of the standard library. Its internal implementation is the time complexity of O (N ^ 2 ).

After KMP algorithm was invented by kknot and others, the time complexity of strstr () function implementation is linear.

There are a lot of online articles on algorithm understanding. I will not explain them here.


Solution code:

Class solution {public: char * strstr (char * haystack, char * needle) {const int n = strlen (haystack), M = strlen (needle); If (! M) return haystack; int next [m], I, j; next [I = 0] = J =-1; // obtain the next array while (I <m-1) {If (j =-1 | needle [I] = needle [J]) next [++ I] = ++ J; else J = next [J];} // pattern matching for (I = J = 0; I <n ;) {If (j =-1 | haystack [I] = needle [J]) ++ I, ++ J; else J = next [J]; if (j = m) return haystack + I-m;} 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.