这种类型的题就是模板题,以后套模板就行了。需要注意的几个地方在注释中给出。
3. 无重复字符的最长子串
中等题
点评:这个题过于简单,以至于模板整体结构都被改掉了,想看模板的建议从下面开始看。
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
window = {}
l, r = 0, 0
res = 0
while r < len(s):
c = s[r]
r += 1
if c in window.keys(): window[c] += 1
else: window[c] = 1
while window[c] > 1:
d = s[l]
l += 1
window[d] -= 1
res = max(r-l, res)
return res
76. 最小覆盖子串
困难题
点评:一切滑动窗口题都可以从这套模板中修改出来。困难题一样秒杀!!!
class Solution:
def minWindow(self, s: str, t: str) -> str:
if len(s) < len(t):return ""
window, need = {}, {}
for c in t:#保存要识别/包含/排列的字符串中的字符及其个数
if c in need.keys(): need[c] += 1
else: need[c] = 1
l, r = 0, 0
N = len(s)
res = ""
valid = 0
while r < N:
c = s[r] #右边移入窗口
r += 1
if c in need:#窗口内的数据更新(只需统计在need中的字符)
if c in window:window[c] += 1
else:window[c] = 1
if window[c] == need[c]:valid += 1
while valid == len(need):
#需要计算的操作,这里是输出最小的子串
if res == "" or r-l < len(res):
res = s[l:r]
d = s[l] #左边移出窗口
l += 1
if d in need:#窗口内的数据更新(只需统计在need中的字符)
if window[d] == need[d]:valid -= 1
window[d] -= 1
return res
438. 找到字符串中所有字母异位词
中等题
点评:秒杀!!!
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(s) < len(p):return []
need, window = {}, {}
for c in p:
if c in need.keys(): need[c] += 1
else: need[c] = 1
l, r = 0, 0
N = len(s)
res = []
valid = 0
while r < N:
cur = s[r]#右入
r += 1
if cur in need.keys():#窗口内操作
if cur in window.keys(): window[cur] += 1
else: window[cur] = 1
if window[cur] == need[cur]:
valid += 1
while r-l >= len(p):
#根据题意选择输出结果
if valid == len(need):
res.append(l)
cur = s[l]#左出
l += 1
if cur in need.keys():#窗口内操作
if window[cur] == need[cur]:
valid -= 1
window[cur] -= 1
return res
567. 字符串的排列
中等题
点评:和上题几乎一样,秒杀!!!
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
if len(s2) < len(s1):return False
need, window = {}, {}
for s in s1:
if s in need.keys(): need[s] += 1
else: need[s] = 1
l, r = 0, 0
valid = 0
while r < len(s2):
c = s2[r]
r += 1
if c in need.keys():
if c in window.keys(): window[c] += 1
else: window[c] = 1
if need[c] == window[c]:
valid += 1
while r-l >= len(s1):
if valid == len(need):
return True
d = s2[l]
l += 1
if d in need.keys():
if need[d] == window[d]:
valid -= 1
window[d] -= 1
return False
总结:
记住模板,忘了来看,来背。