From 0c6a1b3436232fd23a97497dfb5e67dd881a8f84 Mon Sep 17 00:00:00 2001 From: "walkersmith@nuc-14" Date: Tue, 15 Jul 2025 12:39:02 -0400 Subject: [PATCH] solve problem --- .../README.md | 39 +++++++++++++++++++ .../index.js | 17 ++++++++ 2 files changed, 56 insertions(+) create mode 100644 leet-code/28-find-the-index-of-the-first-occurrence-in-a-string/README.md create mode 100644 leet-code/28-find-the-index-of-the-first-occurrence-in-a-string/index.js diff --git a/leet-code/28-find-the-index-of-the-first-occurrence-in-a-string/README.md b/leet-code/28-find-the-index-of-the-first-occurrence-in-a-string/README.md new file mode 100644 index 0000000..4fcf449 --- /dev/null +++ b/leet-code/28-find-the-index-of-the-first-occurrence-in-a-string/README.md @@ -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. diff --git a/leet-code/28-find-the-index-of-the-first-occurrence-in-a-string/index.js b/leet-code/28-find-the-index-of-the-first-occurrence-in-a-string/index.js new file mode 100644 index 0000000..fa8ce4f --- /dev/null +++ b/leet-code/28-find-the-index-of-the-first-occurrence-in-a-string/index.js @@ -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 +}; \ No newline at end of file