Skip to content

Commit e7f20e7

Browse files
committed
Updated 28-find-the-index-of-the-first-occurrence-in-a-string.md
1 parent ec89000 commit e7f20e7

File tree

2 files changed

+31
-7
lines changed

2 files changed

+31
-7
lines changed

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

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,19 +27,31 @@ The first occurrence is at index 0, so we return 0.
2727
- `haystack` and `needle` consist of only lowercase English characters.
2828

2929
## Intuition
30-
Traverse the string once, and if the `needle.length` characters after the current position are equal to `needle`, return the current `index`.
30+
31+
- This kind of question can be solved with one line of code using the built-in `index()`. Obviously, the questioner wants to test our ability to control the loop.
32+
33+
- For `heystack`, traverse each character in turn. There may be two situations:
34+
1. First, the character is not equal to the first letter of `needle`. Then process the next character.
35+
2. Second, if the character is equal to the first letter of `needle`, continue to compare the next character of `heystack` and `needle` in an internal loop until they are not equal or `needle` has completely matched.
36+
37+
- This question is easier to understand by looking at the code directly.
3138

3239
## Complexity
33-
* Time: `O(m * n)`.
40+
* Time: `O(m + n)`.
3441
* Space: `O(n)`.
3542

3643
## Python
3744
```python
3845
class Solution:
3946
def strStr(self, haystack: str, needle: str) -> int:
4047
for i in range(len(haystack)):
41-
if haystack[i:i + len(needle)] == needle:
42-
return i
48+
j = 0
49+
50+
while i + j < len(haystack) and haystack[i + j] == needle[j]:
51+
j += 1
52+
53+
if j == len(needle):
54+
return i
4355

4456
return -1
4557
```
@@ -48,8 +60,14 @@ class Solution:
4860
```javascript
4961
var strStr = function (haystack, needle) {
5062
for (let i = 0; i < haystack.length; i++) {
51-
if (haystack.slice(i, i + needle.length) == needle) {
52-
return i
63+
let j = 0
64+
65+
while (i + j < haystack.length && haystack[i + j] == needle[j]) {
66+
j += 1
67+
68+
if (j == needle.length) {
69+
return i
70+
}
5371
}
5472
}
5573

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

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,13 @@
2727
- `haystack``needle` 仅由小写英文字符组成
2828

2929
## 思路
30-
遍历一遍字符串,如果从当前位置起的后的`needle.length`个字符等于`needle`,则返回当前的`index`
30+
31+
- 这样的题目,如果用内置的`index()`,一行代码就可以实现。显然,出题人是想考察我们对循环的控制能力。
32+
- 针对 `heystack`,依次遍历每个字符。可能出现两种情况:
33+
1. 该字符与`needle`的首字母不相等。这时处理下一个字符。
34+
2. 该字符与`needle`的首字母相等,则在循环中继续比较`heystack`和`needle`的下一个字符,直到不相等或者`needle`已经完全匹配。
35+
36+
- 本题直接看答案比较容易理解。
3137

3238
## 复杂度
3339
* 时间:`O(m * n)`

0 commit comments

Comments
 (0)