3838- 本题直接看答案比较容易理解。
3939
4040## 复杂度
41- * 时间:` O(m * n) ` 。
41+ * 时间:` O(m + n) ` 。
4242* 空间:` O(n) ` 。
4343
4444## Python
4545``` python
4646class 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
5762var 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