"""
题目:给你一个字符串S、一个字符串T,请在字符串S里面找出:包含T所有字母的最小子串。
示例:
输入:S="ADOBECODEBANC", T="ABC
输出:"BANC"
"""
# 方法一 自己写的,但是leetcode上超时
def minWindow(s, t):
m =0
all_in = False
if len(t)==0 or len(s)==0:
return ""
if len(t) > len(s):
return ""
minlength = len(t)
str = []
while True:
for i in range(len(s)-minlength+1):
left = i
right = i + minlength
for k in s[left:right]:
str.append(k)
for j in range(len(t)):
for n in range(len(str)):
if t[j] == str[n]:
m += 1
str.pop(n)
break
if m == len(t):
all_in = True
str = []
m = 0
if all_in:
return s[left:right]
minlength += 1
if minlength == len(s)+1:
return ""
print(minWindow("ADOBECODEBANC", "r"))
print(minWindow("acbbaca", "aba"))
# 方法二 leetcode上的官方解法
from collections import Counter
def minWindow(s, t):
if not t or not s:
return ""
dict_t = Counter(t)
required = len(dict_t) # t中不重复元素的个数
filtered_s = [] # t中元素在s中出现的情况(位置, 值)
for i, char in enumerate(s):
if char in dict_t:
filtered_s.append((i, char))
l, r =0, 0
formed = 0
window_counts = {}
ans = float("inf"), None, None
while r < len(filtered_s):
character = filtered_s[r][1]
window_counts[character] = window_counts.get(character, 0) +1
if window_counts[character] == dict_t[character]:
formed += 1 # 直到t中出现的元素在滑动窗口中全有, 否则一直扩大滑动窗口
while l <= r and formed == required: # 判断窗口是否可以缩小,left右移
character = filtered_s[l][1]
end = filtered_s[r][0]
start = filtered_s[l][0]
if end - start + 1 < ans[0]:
ans = (end - start + 1, start, end)
window_counts[character] -= 1
if window_counts[character] < dict_t[character]:
formed -= 1
l += 1
r += 1
return "" if ans[0] == float("inf") else s[ans[1]:ans[2]+1]
# print(minWindow("ADOBECODEBANC", "ABC"))
print(minWindow("acbbccd", "ad"))
76_最小覆盖子串
最新推荐文章于 2024-03-26 08:30:00 发布