Skip to content

Commit 71d313d

Browse files
committed
docs: 同步第28题到 leetcoder.net 的原始内容
1 parent 58dda9d commit 71d313d

File tree

1 file changed

+37
-6
lines changed

1 file changed

+37
-6
lines changed

zh/1-1000/28-find-the-index-of-the-first-occurrence-in-a-string.md

Lines changed: 37 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -38,16 +38,21 @@
3838
- 本题直接看答案比较容易理解。
3939

4040
## 复杂度
41-
* 时间:`O(m * n)`
41+
* 时间:`O(m + n)`
4242
* 空间:`O(n)`
4343

4444
## Python
4545
```python
4646
class Solution:
4747
def strStr(self, haystack: str, needle: str) -> int:
4848
for i in range(len(haystack)):
49-
if haystack[i:i + len(needle)] == needle:
50-
return i
49+
j = 0
50+
51+
while i + j < len(haystack) and haystack[i + j] == needle[j]:
52+
j += 1
53+
54+
if j == len(needle):
55+
return i
5156

5257
return -1
5358
```
@@ -56,8 +61,14 @@ class Solution:
5661
```javascript
5762
var strStr = function (haystack, needle) {
5863
for (let i = 0; i < haystack.length; i++) {
59-
if (haystack.slice(i, i + needle.length) == needle) {
60-
return i
64+
let j = 0
65+
66+
while (i + j < haystack.length && haystack[i + j] == needle[j]) {
67+
j += 1
68+
69+
if (j == needle.length) {
70+
return i
71+
}
6172
}
6273
}
6374

@@ -90,7 +101,27 @@ var strStr = function (haystack, needle) {
90101
# Welcome to create a PR to complete the code of this language, thanks!
91102
```
92103

93-
## C, Kotlin, Swift, Rust or other languages
104+
## C
105+
```c
106+
// Welcome to create a PR to complete the code of this language, thanks!
107+
```
108+
109+
## Kotlin
110+
```kotlin
111+
// Welcome to create a PR to complete the code of this language, thanks!
112+
```
113+
114+
## Swift
115+
```swift
116+
// Welcome to create a PR to complete the code of this language, thanks!
117+
```
118+
119+
## Rust
120+
```rust
121+
// Welcome to create a PR to complete the code of this language, thanks!
122+
```
123+
124+
## Other languages
94125
```
95126
// Welcome to create a PR to complete the code of this language, thanks!
96127
```

0 commit comments

Comments
 (0)