Skip to content

Commit 2e4175d

Browse files
committed
feat: 0028. Find the Index of the First Occurrence in a String
1 parent 39d6e3b commit 2e4175d

File tree

2 files changed

+112
-0
lines changed

2 files changed

+112
-0
lines changed

Leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/README.md

+41
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,47 @@ seo:
8080
https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/main.go
8181

8282
```go
83+
package findtheindexofthefirstoccurrenceinastring
84+
85+
// 暴力解
86+
// 時間複雜 O(M*N), 空間複雜 O()
87+
func strStr(haystack string, needle string) int {
88+
haystackLen := len(haystack)
89+
needleLen := len(needle)
90+
index := 0
91+
for i := 0; i <= (haystackLen - needleLen); i++ {
92+
j := 0
93+
for j = 0; j < needleLen; j++ {
94+
if haystack[i+j] == needle[j] {
95+
index = i
96+
} else {
97+
break
98+
}
99+
}
100+
if j == needleLen {
101+
return index
102+
}
103+
}
104+
return -1
105+
}
106+
107+
// Slice 解法
108+
func strStrSlice(haystack string, needle string) int {
109+
haystackLen := len(haystack)
110+
needleLen := len(needle)
111+
if haystackLen == 0 || haystackLen < needleLen {
112+
return -1
113+
}
114+
if needleLen == 0 {
115+
return 0
116+
}
117+
for i := 0; i <= (haystackLen - needleLen); i++ {
118+
if haystack[i:i+needleLen] == needle {
119+
return i
120+
}
121+
}
122+
return -1
123+
}
83124

84125
```
85126

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// 時間複雜度:
2+
// 空間複雜度:
3+
/*
4+
* @lc app=leetcode.cn id=28 lang=golang
5+
*
6+
* [28] 找出字符串中第一个匹配项的下标
7+
*
8+
* https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/description/
9+
*
10+
* algorithms
11+
* Easy (43.50%)
12+
* Likes: 2214
13+
* Dislikes: 0
14+
* Total Accepted: 1.1M
15+
* Total Submissions: 2.4M
16+
* Testcase Example: '"sadbutsad"\n"sad"'
17+
*
18+
* 给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0
19+
* 开始)。如果 needle 不是 haystack 的一部分,则返回  -1 。
20+
*
21+
*
22+
*
23+
* 示例 1:
24+
*
25+
*
26+
* 输入:haystack = "sadbutsad", needle = "sad"
27+
* 输出:0
28+
* 解释:"sad" 在下标 0 和 6 处匹配。
29+
* 第一个匹配项的下标是 0 ,所以返回 0 。
30+
*
31+
*
32+
* 示例 2:
33+
*
34+
*
35+
* 输入:haystack = "leetcode", needle = "leeto"
36+
* 输出:-1
37+
* 解释:"leeto" 没有在 "leetcode" 中出现,所以返回 -1 。
38+
*
39+
*
40+
*
41+
*
42+
* 提示:
43+
*
44+
*
45+
* 1 <= haystack.length, needle.length <= 10^4
46+
* haystack 和 needle 仅由小写英文字符组成
47+
*
48+
*
49+
*/
50+
51+
// @lc code=start
52+
func strStr(haystack string, needle string) int {
53+
hLen := len(haystack)
54+
nLen := len(needle)
55+
if hLen < 0 || hLen < nLen {
56+
return -1
57+
}
58+
if nLen == 0 {
59+
return 0
60+
}
61+
62+
for i := 0; i <= (hLen - nLen); i++ {
63+
if haystack[i:i+nLen] == needle {
64+
return i
65+
}
66+
}
67+
return -1
68+
}
69+
70+
// @lc code=end
71+

0 commit comments

Comments
 (0)