In this LeetCode challenge, we’re asked to write a function similar to C++’s StrStr. By way of a quick refresher, StrStr is a function that takes two strings; string A (the haystack) and string B (the needle), and returns whether (and where) you can find string B in string A (the needle in the haystack).
In other words, if provided with a haystack of
hello , and a needle of
lo , StrStr would return 3, as that is where the needle appears in the haystack. According to the LeetCode spec, if we cannot find the needle in the haystack, we should return -1, and if the needle is empty, we should return 0.
Solution 1: Loop
This solution loops through the haystack until it finds the start of the needle, and then checks if the letters that follow in the haystack match that of the needle. If a full match is detected, then this position is returned, otherwise the traversal of the haystack continues. If we reach the end of the haystack without finding the needle (or more accurately, if we traverse far enough into the haystack that the needle cannot be found), we return -1.