nathanwailes

LeetCode 567 - Permutation in String - 2022.12.28 solution - fixed to pass all LC tests

Dec 29th, 2022
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.40 KB | None | 0 0
  1. class Solution:
  2.     def checkInclusion(self, s1: str, s2: str) -> bool:
  3.         # How to solve it: Sliding window.
  4.         # Create a dict count of s1.  This is the target.
  5.         # Have two pointers in s2.  Advance the left pointer until you find a
  6.         # character that is in the s1 dict.  Then start advancing the right pointer.
  7.         # As you advance the right pointer, add to a dict
  8.         # count of the characters in the current window in s2.  Also have a variable
  9.         # 'required_matches_remaining' that contains the number of characters in s1
  10.         # that need to have their exact counts matched in the current window in s2.
  11.         # When you add a new character to the s2 dict, compare its count to the s1 dict,
  12.         # and if the count is switching to exactly correct, decrement the
  13.         # required_matches variable; if the count is switching from exactly correct to
  14.         # too much, this won't be a permutation and you need to start advancing the left
  15.         # pointer again.  If the right pointer hits a character not in the s1 dict, you
  16.         # need to start advancing the left pointer again.
  17.  
  18.         # Fill out the s1 (target) dict:
  19.         s1_dict = dict()
  20.         for char in s1:
  21.             if char not in s1_dict:
  22.                 s1_dict[char] = 1
  23.             else:
  24.                 s1_dict[char] += 1
  25.        
  26.         s2_dict = defaultdict(int)
  27.         l = 0
  28.         # We want to keep going as long as the left pointer is suitably far from the end
  29.         while l <= len(s2) - len(s1):
  30.             # If the character isn't even in the s1 dict, don't bother doing anything
  31.             if s2[l] not in s1_dict:
  32.                 pass
  33.             else:
  34.                 r = l
  35.                 remaining_characters_to_match = len(s1_dict.keys())
  36.                 while r <= len(s2):
  37.                     if remaining_characters_to_match == 0:
  38.                         return True
  39.                    
  40.                     char = s2[r]
  41.                     s2_dict[char] += 1
  42.                     if char not in s1_dict or s2_dict[char] > s1_dict[char]:
  43.                         break
  44.                     elif s2_dict[char] == s1_dict[char]:
  45.                         remaining_characters_to_match -= 1
  46.                     r += 1
  47.  
  48.             s2_dict.clear()
  49.             l += 1
  50.        
  51.         # If we haven't found a suitable substring by now, return False
  52.         return False
Advertisement
Add Comment
Please, Sign In to add comment