LeetCode-- primary algorithms - to achieve strstr ()

Achieve strStr ()

Achieve strStr () function.

Given a string and a needle haystack string, a position of the needle to find the first occurrence of the string (starting from 0) in the haystack string. If not, it returns -1.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1
Description:

When the needle is an empty string, the return value of what we should do? This is a good question in the interview.

For this question, when the needle is an empty string when we should return 0. This is consistent with the C language strstr () and Java's indexOf () definition.

Ideas:

The first two strings simultaneously traversing determines if the character corresponding to the same, the two string pointer positions i and j are increased by one, if not identical, only the pointer i is incremented by one and haystack needle scratch, when i = i - j +1.
Where i = i - j +1; string because the same time, I had j + 1 times, and when again encounter the same time. Need a pointer back to the same time, it is determined.
eg:
I input
"helllo"
"LLO"
My standard output
I = 1J = 0
I = 2J = 0
I = 3j =. 1
I =. 4J = 2
I = 3j = 0
I =. 4J =. 1
I =. 5J = 2
i = 6j = 3

Code:

class Solution {
public:
    int strStr(string haystack, string needle) {
        //needle为空,返回0
        if(needle.length()<1)
            return 0;
        
        int i = 0;
        int j = 0;
        
        while(i < haystack.length() && j < needle.length())
        {
            if(haystack[i] == needle[j])
            {
                i = i+1;
                j = j+1;
            }
            else
            {
                i = i -j +1;
                j = 0;
            }
            cout << "i = "<<i<<"j="<<j<<endl; 
        }
        if( j == needle.length())
            return i-j;
        return -1;
    }
};
Published 61 original articles · won praise 89 · Views 200,000 +

Guess you like

Origin blog.csdn.net/qq_33559992/article/details/87889684