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
Original link:[leetcoder.net - LeetCoder: Fucking Good LeetCode Solutions](https://leetcoder.net/en/leetcode/28-find-the-index-of-the-first-occurrence-in-a-string)
2
2
3
3
#28. Find the Index of the First Occurrence in a String - LeetCoder: Fucking Good LeetCode Solutions
4
+
4
5
LeetCode link:[28. Find the Index of the First Occurrence in a String](https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string), Difficulty:**Easy**.
5
6
6
7
##LeetCode description of "28. Find the Index of the First Occurrence in a String"
8
+
7
9
Given two strings`needle` and`haystack`, return the**index** of the first occurrence of`needle` in`haystack`, or`-1` if`needle` is not part of`haystack`.
**Explanation**:`"leeto" did not occur in "leetcode", so we return -1.`
28
+
**Explanation**:
29
+
30
+
"leeto" did not occur in "leetcode", so we return -1.
26
31
27
32
###[Constraints]
33
+
28
34
-`1 <= haystack.length, needle.length <= 10000`
29
35
-`haystack` and`needle` consist of only lowercase English characters.
30
36
31
37
##Intuition
38
+
32
39
- 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.
33
40
34
41
- For`heystack`, traverse each character in turn. There may be two situations:
@@ -38,39 +45,49 @@ The first occurrence is at index 0, so we return 0.
38
45
- This question is easier to understand by looking at the code directly.
39
46
40
47
##Complexity
48
+
41
49
- Time complexity:`O(N + M)`.
42
50
- Space complexity:`O(1)`.
43
51
44
52
##Python
53
+
45
54
```python
46
55
classSolution:
47
56
defstrStr(self,haystack:str,needle:str) ->int:
48
57
for iinrange(len(haystack)):
49
58
j=0
59
+
50
60
while i+ j<len(haystack)and haystack[i+ j]== needle[j]:
51
61
j+=1
62
+
52
63
if j==len(needle):
53
64
return i
65
+
54
66
return-1
55
67
```
56
68
57
69
##JavaScript
70
+
58
71
```javascript
59
72
varstrStr=function (haystack,needle) {
60
73
for (let i=0; i<haystack.length; i++) {
61
74
let j=0
75
+
62
76
while (i+ j<haystack.length&& haystack[i+ j]== needle[j]) {
63
-
j+=1
64
-
if (j==needle.length) {
65
-
return i
66
-
}
77
+
j+=1
78
+
79
+
if (j==needle.length) {
80
+
return i
81
+
}
67
82
}
68
83
}
84
+
69
85
return-1
70
86
};
71
87
```
72
88
73
89
##Other languages
90
+
74
91
```java
75
92
// Welcome to create a PR to complete the code of this language, thanks!