Leetcode(10) - implements strStr()

Implement  the strStr()  function.

Given a haystack string and a needle string, find the first position (0-based) in the haystack string where the needle string occurs. Returns -1 if not present.

needle We should return 0 when it  is an empty string.

The initial idea: use i and j to traverse the haystack and needle strings respectively from the beginning, fix j first, and stop traversing until the letter pointed to by i is equal to the first character of the needle. Then i and j start to traverse backwards at the same time. If there is an unequal one, return -1 until a string comes first. If haystack comes first, return -1, if needle comes first or both ends, return i-needle.size()

There is a problem with this way of thinking, that is, strings such as mississip and issip, that is, if a part similar to a substring but not equal to a substring appears in the parent string first, it will cause interference.

So here we change the way of thinking: we traverse the substrings of the substring length in turn in the mother string to see if we can find the part equal to the substring, so that the above part will not be missed.

int strStr(string haystack, string needle) 
{
        if (needle.empty()) return 0;
        int m = haystack.size(), n = needle.size();
        if (m < n) return -1;
        for (int i = 0; i <= m - n; ++i) 
     {
int j = 0; for (j = 0; j < n; ++j)
       {
if (haystack[i + j] != needle[j]) break; } if (j == n)
           return i; } return -1; }

In fact, we can also use the ready-made find function in the string class

int strStr(string haystack, string needle) 
{
    string::size_type index = haystack.find(needle);
    return index == string::npos ? -1 : index;
}

The find function only uses the first parameter. The default is to search from the beginning of the parent string. If it finds the same substring as needle, it stops and returns the position. If it is not found, it returns string::npos.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325127273&siteId=291194637