Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# 28-find-the-index-of-the-first-occurrence-in-a-string

Given two strings `needle` and `haystack`, return the index of the first occurrence of `needle` in `haystack`, or -1 if `needle` is not part of `haystack`.

---

### Example 1:

**Input:**
`haystack = "sadbutsad"`
`needle = "sad"`

**Output:**
`0`

**Explanation:**
"sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.

---

### Example 2:

**Input:**
`haystack = "leetcode"`
`needle = "leeto"`

**Output:**
`-1`

**Explanation:**
"leeto" did not occur in "leetcode", so we return -1.

---

### Constraints:

- `1 <= haystack.length, needle.length <= 10^4`
- `haystack` and `needle` consist of only lowercase English characters.
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function(haystack, needle) {
// needles can't exceed the length of the haystack
if (haystack.length < needle.length) return -1;

// stop searching once the remaining characters aren't at least as long as needle
for (let i = 0; i <= haystack.length - needle.length; i++) {
// the needle is found
if (haystack.substring(i, i + needle.length) === needle) return i
}
// fallback to not found
return -1
};