Find the Index of the First Occurrence in a String

Easy String

Problem

Return the first index where needle appears in haystack, or -1 if it does not appear.

Original: LeetCode 28: Find the Index of the First Occurrence in a String.

Examples

Example 1

Input`haystack = "sadbutsad", needle = "sad"`
Output`0`

Example 2

Input`haystack = "leetcode", needle = "leeto"`
Output`-1`

Constraints

  • 1 <= haystack.length, needle.length <= 10^4
  • haystack and needle consist of only lowercase English characters.

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (1)
  1. LeetCode 28: Find the Index of the First Occurrence in a Stringleetcode.com