Skip to content

Commit

Permalink
feat: 0028. Find the Index of the First Occurrence in a String
Browse files Browse the repository at this point in the history
  • Loading branch information
kimi0230 committed May 6, 2024
1 parent 39d6e3b commit 2e4175d
Show file tree
Hide file tree
Showing 2 changed files with 112 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,47 @@ seo:
https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/main.go

```go
package findtheindexofthefirstoccurrenceinastring

// 暴力解
// 時間複雜 O(M*N), 空間複雜 O()
func strStr(haystack string, needle string) int {
haystackLen := len(haystack)
needleLen := len(needle)
index := 0
for i := 0; i <= (haystackLen - needleLen); i++ {
j := 0
for j = 0; j < needleLen; j++ {
if haystack[i+j] == needle[j] {
index = i
} else {
break
}
}
if j == needleLen {
return index
}
}
return -1
}

// Slice 解法
func strStrSlice(haystack string, needle string) int {
haystackLen := len(haystack)
needleLen := len(needle)
if haystackLen == 0 || haystackLen < needleLen {
return -1
}
if needleLen == 0 {
return 0
}
for i := 0; i <= (haystackLen - needleLen); i++ {
if haystack[i:i+needleLen] == needle {
return i
}
}
return -1
}

```

Expand Down
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

0 comments on commit 2e4175d

Please sign in to comment.