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