Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def checkInclusion(self, s1: str, s2: str) -> bool:
- """ We can't just check if the characters (and their numbers) of s1 is in
- s2 because all the characters need to be adjacent.
- """
- chars_in_s1 = _get_chars_in_s1(s1)
- chars_to_counts = _get_initial_window(s1, s2)
- l = 0
- r = len(s1)
- while r <= len(s2):
- if _chars_are_the_same(chars_in_s1, chars_to_counts):
- return True
- chars_to_counts[s2[l]] -= 1
- if r < len(s2):
- chars_to_counts[s2[r]] += 1
- l += 1
- r += 1
- return False
- def _chars_are_the_same(chars_in_s1, chars_to_counts):
- for c in chars_in_s1.keys():
- if chars_to_counts[c] != chars_in_s1[c]:
- return False
- return True
- def _get_chars_in_s1(s1):
- chars_in_s1 = defaultdict(int)
- for c in s1:
- chars_in_s1[c] += 1
- return chars_in_s1
- def _get_initial_window(s1, s2):
- chars_to_counts = defaultdict(int)
- if len(s2) == 0:
- return chars_to_counts
- for i, c in enumerate(s2):
- if i >= len(s1):
- return chars_to_counts
- chars_to_counts[c] += 1
- return chars_to_counts
Advertisement
Add Comment
Please, Sign In to add comment