38
38
- 本题直接看答案比较容易理解。
39
39
40
40
## 复杂度
41
- * 时间:` O(m * n) ` 。
41
+ * 时间:` O(m + n) ` 。
42
42
* 空间:` O(n) ` 。
43
43
44
44
## Python
45
45
``` python
46
46
class Solution :
47
47
def strStr (self , haystack : str , needle : str ) -> int :
48
48
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
51
56
52
57
return - 1
53
58
```
@@ -56,8 +61,14 @@ class Solution:
56
61
``` javascript
57
62
var strStr = function (haystack , needle ) {
58
63
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
+ }
61
72
}
62
73
}
63
74
@@ -90,7 +101,27 @@ var strStr = function (haystack, needle) {
90
101
# Welcome to create a PR to complete the code of this language, thanks!
91
102
```
92
103
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
94
125
```
95
126
// Welcome to create a PR to complete the code of this language, thanks!
96
127
```
0 commit comments