Find the First Substring Occurrence
Problem statement
Given two nonempty lowercase strings haystack and needle, return the zero-based starting index of the first complete occurrence of needle in haystack. Return -1 if no complete occurrence exists.
Occurrences may overlap. An occurrence must match every character of needle in order.
Function
findFirstOccurrence(haystack: String, needle: String) → intExamples
Example 1
haystack = "abababac"needle = "ababac"return = 2The prefix at index 0 differs before the needle ends; the complete match starts at index 2.
Example 2
haystack = "mississippi"needle = "issi"return = 1The first complete issi begins at index 1.
Example 3
haystack = "aaaaa"needle = "bba"return = -1No starting position matches the complete needle.
Constraints
1 <= haystack.length, needle.length <= 10000.- Both strings contain only lowercase English letters.