Advertisement
smj007

Untitled

Aug 7th, 2023
954
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.91 KB | None | 0 0
  1. """
  2. Maintain a sliding window of constant length s1. Keep adding from the right and removing from left from the hashmap counter
  3. and compare the dictionary. If equal return True.
  4. """
  5.  
  6.  
  7. class Solution:
  8.     def checkInclusion(self, s1: str, s2: str) -> bool:
  9.  
  10.         counter_s1 = {}
  11.         window_s2 = {}
  12.  
  13.         for c in s1:
  14.             counter_s1[c] = counter_s1.get(c, 0) + 1
  15.  
  16.         left = 0
  17.         for c in s2[:len(s1)-1]:
  18.             window_s2[c] = window_s2.get(c, 0) + 1
  19.  
  20.         for right in range(len(s1)-1, len(s2)):
  21.             window_s2[s2[right]] = window_s2.get(s2[right], 0) + 1
  22.  
  23.             if counter_s1 == window_s2:
  24.                 return True
  25.             else:
  26.                 window_s2[s2[left]] = window_s2.get(s2[left], 0) - 1
  27.                 if window_s2[s2[left]] == 0:
  28.                     window_s2.pop(s2[left])
  29.                 left = left + 1
  30.    
  31.         return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement