Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit de72f59

Browse files
🐱(sw): 567. 字符串的排列 补充优化方案
1 parent f28b82f commit de72f59

File tree

1 file changed

+54
-1
lines changed

1 file changed

+54
-1
lines changed

‎docs/algorithm/sliding-window/README.md‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,4 +154,57 @@ class Solution:
154154
```
155155

156156
- 时间复杂度:$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+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /