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 ()