nathanwailes

LeetCode 567 - Permutation in String - 2023.10.15 solution

Oct 14th, 2023
1,784
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.29 KB | None | 0 0
  1. class Solution:
  2.     def checkInclusion(self, s1: str, s2: str) -> bool:
  3.         """ We can't just check if the characters (and their numbers) of s1 is in
  4.        s2 because all the characters need to be adjacent.
  5.        """
  6.         chars_in_s1 = _get_chars_in_s1(s1)
  7.         chars_to_counts = _get_initial_window(s1, s2)
  8.        
  9.         l = 0
  10.         r = len(s1)
  11.        
  12.         while r <= len(s2):
  13.             if _chars_are_the_same(chars_in_s1, chars_to_counts):
  14.                 return True
  15.    
  16.             chars_to_counts[s2[l]] -= 1
  17.  
  18.             if r < len(s2):
  19.                 chars_to_counts[s2[r]] += 1
  20.    
  21.             l += 1
  22.             r += 1
  23.    
  24.         return False
  25.  
  26.  
  27. def _chars_are_the_same(chars_in_s1, chars_to_counts):
  28.     for c in chars_in_s1.keys():
  29.         if chars_to_counts[c] != chars_in_s1[c]:
  30.             return False
  31.     return True
  32.  
  33.  
  34. def _get_chars_in_s1(s1):
  35.     chars_in_s1 = defaultdict(int)
  36.     for c in s1:
  37.         chars_in_s1[c] += 1
  38.     return chars_in_s1
  39.  
  40.  
  41. def _get_initial_window(s1, s2):
  42.     chars_to_counts = defaultdict(int)
  43.     if len(s2) == 0:
  44.         return chars_to_counts
  45.     for i, c in enumerate(s2):
  46.         if i >= len(s1):
  47.             return chars_to_counts
  48.         chars_to_counts[c] += 1
  49.     return chars_to_counts
  50.  
Advertisement
Add Comment
Please, Sign In to add comment