pavel_777

leet minimum-window-substring

Jul 17th, 2022 (edited)
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. # https://leetcode.com/problems/minimum-window-substring/
  2. from collections import defaultdict, Counter
  3.  
  4.  
  5. class Solution:
  6.     def minWindow(self, s: str, t: str) -> str:
  7.         res = ''
  8.         if not s or not t:
  9.             return res
  10.  
  11.         d = dict(Counter(t))
  12.         n = len(d)
  13.  
  14.         d_cur = defaultdict(int)
  15.         idx_good = defaultdict(bool)
  16.         idx_good_count = 0
  17.  
  18.         l, r = 0, -1
  19.         while True:
  20.             if idx_good_count < n:
  21.                 r += 1
  22.                 if r > len(s) - 1:
  23.                     break
  24.  
  25.                 ch = s[r]
  26.                 if ch in d:
  27.                     d_cur[ch] += 1
  28.                     if d_cur[ch] >= d[ch] and not idx_good[ch]:
  29.                         idx_good[ch] = True
  30.                         idx_good_count += 1
  31.             else:
  32.                 l += 1
  33.                 prev_ch = s[l - 1]
  34.                 if prev_ch in d:
  35.                     d_cur[prev_ch] -= 1
  36.                     if d_cur[prev_ch] < d[prev_ch] and idx_good[prev_ch]:
  37.                         idx_good[prev_ch] = False
  38.                         idx_good_count -= 1
  39.  
  40.             if idx_good_count == n:
  41.                 if (res and len(s[l:r + 1]) < len(res)) or not res:
  42.                     res = s[l:r + 1]
  43.  
  44.         return res
  45.  
Add Comment
Please, Sign In to add comment