from collections import Counter, defaultdict defminWindow(self, s: str, t: str) -> str: needs = dict(Counter(t)) left = right = 0 counter = len(t) min_len = float('inf') res = '' # search [left. right) while right < len(s): c = s[right] if c in needs: # is a valid character needs[c] -= 1 counter -= needs[c] >= 0
right += 1 whilenot counter: # update res if (right - left) < min_len: min_len = right - left res = s[left: right] c = s[left] if c in needs: needs[c] += 1 counter += needs[c] > 0 left += 1 return res
from collections import Counter defcheckInclusion(self, s1: str, s2: str) -> bool: needs = Counter(s1) counter = len(s1) left = right = 0 while right < len(s2): c = s2[right] if c in needs: needs[c] -= 1 counter -= needs[c] >= 0 right += 1 whilenot counter: if right - left == len(s1): returnTrue c = s2[left] if c in needs: needs[c] += 1 counter += needs[c] > 0 left += 1 returnFalse
from collections import Counter deffindAnagrams(self, s: str, p: str) -> List[int]: needs = Counter(p) counter = len(p) left = right = 0 res = [] while right < len(s): c = s[right] if c in needs: needs[c] -= 1 counter -= needs[c] >= 0 right += 1 # is a valid window whilenot counter: c = s[left] if (right - left) == len(p): res.append(left) if c in needs: needs[c] += 1 counter += needs[c] > 0 left += 1 return res
3. Longest Substring Without Repeating Characters
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
from collections import defaultdict deflengthOfLongestSubstring(self, s: str) -> int: cur = defaultdict(int) left = right = 0 res = 0 while right < len(s): cur[s[right]] += 1 while cur[s[right]] > 1: cur[s[left]] -= 1 left += 1 right += 1 res = max(res, right - left) return res
from collections import deque defmaxSlidingWindow(self, nums: List[int], k: int) -> List[int]: defwindow_push(n): # delete all element less than n while window and window[-1] < n: window.pop() window.append(n) defwindow_get_max(): return window[0] if window elseNone defwindow_pop(n): return window.popleft() if window and n == window[0] elseNone window = deque([]) res = [] for i, n inenumerate(nums): window_push(n) if i >= k - 1: # generate res when i >= k - 1 res.append(window_get_max()) # remove left window_pop(nums[i - k + 1]) return res