nathanwailes

LeetCode 567 - Permutation in String - NeetCode solution

Oct 14th, 2023
1,504
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | None | 0 0
  1. class Solution:
  2.     def checkInclusion(self, s1: str, s2: str) -> bool:
  3.         if len(s1) > len(s2): return False
  4.  
  5.         s1Count, s2Count = [0] * 26, [0] * 26
  6.         for i in range(len(s1)):
  7.             s1Count[ord(s1[i]) - ord('a')] += 1
  8.             s2Count[ord(s2[i]) - ord('a')] += 1
  9.        
  10.         matches = 0
  11.         for i in range(26):
  12.             matches += (1 if s1Count[i] == s2Count[i] else 0)
  13.        
  14.         l = 0
  15.         for r in range(len(s1), len(s2)):
  16.             if matches == 26: return True
  17.  
  18.             index = ord(s2[r]) - ord('a')
  19.             s2Count[index] += 1
  20.             if s1Count[index] == s2Count[index]:
  21.                 matches += 1
  22.             elif s1Count[index] + 1 == s2Count[index]:
  23.                 matches -= 1
  24.            
  25.             index = ord(s2[l]) - ord('a')
  26.             s2Count[index] -= 1
  27.             if s1Count[index] == s2Count[index]:
  28.                 matches += 1
  29.             elif s1Count[index] - 1 == s2Count[index]:
  30.                 matches -= 1
  31.             l += 1
  32.         return matches == 26
  33.  
Advertisement
Add Comment
Please, Sign In to add comment