You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: en/1-1000/28-find-the-index-of-the-first-occurrence-in-a-string.md
+24-6Lines changed: 24 additions & 6 deletions
Original file line number
Diff line number
Diff line change
@@ -27,19 +27,31 @@ The first occurrence is at index 0, so we return 0.
27
27
-`haystack` and`needle` consist of only lowercase English characters.
28
28
29
29
##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.
31
38
32
39
##Complexity
33
-
* Time:`O(m* n)`.
40
+
* Time:`O(m+ n)`.
34
41
* Space:`O(n)`.
35
42
36
43
##Python
37
44
```python
38
45
classSolution:
39
46
defstrStr(self,haystack:str,needle:str) ->int:
40
47
for iinrange(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
43
55
44
56
return-1
45
57
```
@@ -48,8 +60,14 @@ class Solution:
48
60
```javascript
49
61
varstrStr=function (haystack,needle) {
50
62
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]) {