The C function library has a function strstr (char*, char*), which implements finding a substring in an original string. Suppose that a substring is found that returns the starting position of the substring in the original string, if no such substring is found. Then NULL is returned.
However, the function library only implements lookups in the normal case. That is, there is not much optimization in running some special strings when the efficiency is very low, so in a very many interviews to improve the algorithm, to achieve a high efficiency of the STRSTR algorithm, here, I have a few modifications to the original algorithm. In the case of certain special measurements. The running efficiency is really much higher than the original algorithm, here, the implementation code is posted. Modify the place in the implementation already has the gaze. Of course, friends have a more efficient way to achieve, please do not be stingy with your generous enlighten:
The code looks like the following:
#include <cstring> #include <iostream> #include <cassert>using namespace std;char* my_strstr (char* STR, char* sub) {assert (str = null); assert (sub! = null); int str_len = strlen (str); int sub_len = strlen (sub); if (Str_len &L T Sub_len)/* No comparison. Certainly not */{return NULL;} if (Str_len! = 0 && sub_len = 0)/*aaaaaaaaaaaaaaaaaa, "", it takes a lot more time */{cout << "substring is empty.。 "<< Endl;return NULL;} if (Str_len = = 0 && Sub_len = = 0)/* are NULL to return directly */{cout << "the original string and substring are empty. "<< Endl;return str;} for (int i = 0; I! = strlen (str); ++i) {int m = 0, n = i;cout << "The remaining length of the original string:" << strlen (str + i) << Endl; cout << "substring length:" << sub_len << endl;if (strlen (str + i) < Sub_len)/* Look back and assume the length of the original string is not enough. It's definitely not */{cout << "The substring is too long.
。 "<< Endl;return NULL;} if (str[n] = = Sub[m]) {while (str[n++] = = sub[m++]) {if (sub[m] = = ' + ') {return str + i;}}}} return NULL;}
Efficient implementation of C-function strstr