提交 5f029526 编写于 作者: J J.J. Liu 提交者: labuladong

Update 滑动窗口技巧.md

上级 18288033
......@@ -295,8 +295,47 @@ while (right < s.size()) {
![公众号 labuladong](../pictures/labuladong.png)
[Jiajun](https://github.com/liujiajun) 提供最小覆盖子串 Python3 代码:
```python3
class Solution:
def minWindow(self, s: str, t: str) -> str:
# 最短子串开始位置和长度
start, min_len = 0, float('Inf')
left, right = 0, 0
res = s
# 两个计数器
needs = Counter(t)
window = collections.defaultdict(int)
# defaultdict在访问的key不存在的时候返回默认值0, 可以减少一次逻辑判断
match = 0
while right < len(s):
c1 = s[right]
if needs[c1] > 0:
window[c1] += 1
if window[c1] == needs[c1]:
match += 1
right += 1
while match == len(needs):
if right - left < min_len:
# 更新最小子串长度
min_len = right - left
start = left
c2 = s[left]
if needs[c2] > 0:
window[c2] -= 1
if window[c2] < needs[c2]:
match -= 1
left += 1
return s[start:start+min_len] if min_len != float("Inf") else ""
```
[上一篇:二分查找解题框架](../算法思维系列/二分查找详解.md)
[下一篇:双指针技巧解题框架](../算法思维系列/双指针技巧.md)
[目录](../README.md#目录)
\ No newline at end of file
[目录](../README.md#目录)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册