Find the Index of the First Occurrence
Easy · string matching
You are given two strings, haystack and needle, both made of lowercase letters.
Return the index of the first place where needle appears inside haystack as one unbroken block of characters. Positions start at 0. If needle does not appear anywhere in haystack, return -1.
Occurrences may overlap, and needle can be longer than haystack (in which case it cannot appear).
Examples
Example 1
Input: haystack = "sleepsoundly", needle = "sound"
Output: 5
The block "sound" starts at index 5 of "sleepsoundly".
Example 2
Input: haystack = "abcdef", needle = "xyz"
Output: -1
None of the blocks of length 3 in the haystack equals the needle.
Example 3
Input: haystack = "aaa", needle = "aa"
Output: 0
The needle appears at index 0 and again at index 1. The first one counts.
Constraints
- 1 <= len(haystack) <= 10^4
- 1 <= len(needle) <= 10^4
- haystack and needle contain only lowercase letters