Leetcode notes: Implement strStr ()

Source: Internet
Author: User

I. Title Description

Implement strStr ().
Returns A pointer to the first occurrence of needle in haystack, or null if needle are not part of haystack.

Two. Topic analysis

Implement the Strstr () function. Returns the position of the first occurrence of the needle (keyword) in haystack (string), or 1 if needle is not in haystack. Because the time complexity of using the brute force method is O (MN) times out, it can be solved using the famous KMP algorithm. This is a string matching algorithm proposed by Knuth,morris,pratt, which is a very good string matching algorithm for any string and target string, it can complete the matching search in linear time.

Three. Sample code

KMP algorithm:

classSolution { Public:voidGetNext ( vector<int>&next,string&needle) {inti =0, j =-1; Next[i] = j; while(I! = Needle.length ()) { while(J! =-1&& needle[i]! = needle[j]) j = next[j];        Next[++i] = ++j; }    }intSTRSTR (stringHaystackstringNeedle) {if(Haystack.empty ())returnNeedle.empty ()?0: -1;if(Needle.empty ())return 0; vector<int>Next (Needle.length () +1); GetNext (Next, needle);inti =0, j =0; while(I! = Haystack.length ()) { while(J! =-1&& haystack[i]! = needle[j]) j = next[j]; ++i; ++j;if(j = = Needle.length ())returnI-j; }return-1; }};

Four. Summary

For this problem, there are some other well-known algorithms, such as the Rabin-karp and Boyer-moore algorithms.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode notes: Implement strStr ()

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.