-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: 0028. Find the Index of the First Occurrence in a String
- Loading branch information
Showing
2 changed files
with
112 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
// 時間複雜度: | ||
// 空間複雜度: | ||
/* | ||
* @lc app=leetcode.cn id=28 lang=golang | ||
* | ||
* [28] 找出字符串中第一个匹配项的下标 | ||
* | ||
* https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/description/ | ||
* | ||
* algorithms | ||
* Easy (43.50%) | ||
* Likes: 2214 | ||
* Dislikes: 0 | ||
* Total Accepted: 1.1M | ||
* Total Submissions: 2.4M | ||
* Testcase Example: '"sadbutsad"\n"sad"' | ||
* | ||
* 给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 | ||
* 开始)。如果 needle 不是 haystack 的一部分,则返回 -1 。 | ||
* | ||
* | ||
* | ||
* 示例 1: | ||
* | ||
* | ||
* 输入:haystack = "sadbutsad", needle = "sad" | ||
* 输出:0 | ||
* 解释:"sad" 在下标 0 和 6 处匹配。 | ||
* 第一个匹配项的下标是 0 ,所以返回 0 。 | ||
* | ||
* | ||
* 示例 2: | ||
* | ||
* | ||
* 输入:haystack = "leetcode", needle = "leeto" | ||
* 输出:-1 | ||
* 解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。 | ||
* | ||
* | ||
* | ||
* | ||
* 提示: | ||
* | ||
* | ||
* 1 <= haystack.length, needle.length <= 10^4 | ||
* haystack 和 needle 仅由小写英文字符组成 | ||
* | ||
* | ||
*/ | ||
|
||
// @lc code=start | ||
func strStr(haystack string, needle string) int { | ||
hLen := len(haystack) | ||
nLen := len(needle) | ||
if hLen < 0 || hLen < nLen { | ||
return -1 | ||
} | ||
if nLen == 0 { | ||
return 0 | ||
} | ||
|
||
for i := 0; i <= (hLen - nLen); i++ { | ||
if haystack[i:i+nLen] == needle { | ||
return i | ||
} | ||
} | ||
return -1 | ||
} | ||
|
||
// @lc code=end | ||
|