File tree Expand file tree Collapse file tree 1 file changed +54
-1
lines changed
docs/algorithm/sliding-window Expand file tree Collapse file tree 1 file changed +54
-1
lines changed Original file line number Diff line number Diff line change @@ -154,4 +154,57 @@ class Solution:
154
154
```
155
155
156
156
- 时间复杂度:$O(l1 + (l2 - l1) * 26)$($l1$ 为字符串 s1 长度,$l2$ 为字符串 s2 长度)
157
- - 空间复杂度:$O(1)$
157
+ - 空间复杂度:$O(1)$
158
+
159
+ 优化一下:
160
+
161
+ ``` python
162
+ class Solution :
163
+ def checkInclusion (self , s1 : str , s2 : str ) -> bool :
164
+ length1 = len (s1)
165
+ length2 = len (s2)
166
+ if length2 < length1:
167
+ return False
168
+
169
+ count1 = [0 for _ in range (26 )]
170
+ count2 = [0 for _ in range (26 )]
171
+
172
+ ord_a = ord (' a' )
173
+
174
+ for i in range (length1):
175
+ c1 = s1[i]
176
+ c2 = s2[i]
177
+ count1[ord (c1) - ord_a] += 1
178
+ count2[ord (c2) - ord_a] += 1
179
+
180
+ # 计算相同字母位数
181
+ count = 0
182
+ for i in range (26 ):
183
+ if count1[i] == count2[i]:
184
+ count += 1
185
+
186
+ for i in range (length1, length2):
187
+
188
+ if count == 26 :
189
+ return True
190
+
191
+ left_c = s2[i - length1]
192
+ left_index = ord (left_c) - ord_a
193
+ right_c = s2[i]
194
+ right_index = ord (right_c) - ord_a
195
+
196
+ if count2[left_index] == count1[left_index]:
197
+ count -= 1
198
+ if count2[right_index] == count1[right_index]:
199
+ count -= 1
200
+
201
+ count2[left_index] -= 1
202
+ count2[right_index] += 1
203
+
204
+ if count2[left_index] == count1[left_index]:
205
+ count += 1
206
+ if count2[right_index] == count1[right_index]:
207
+ count += 1
208
+
209
+ return count == 26
210
+ ```
You can’t perform that action at this time.
0 commit comments