-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path4. Permutation in String.py
59 lines (47 loc) · 2.21 KB
/
4. Permutation in String.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
s1_count = Counter(s1)
l, r = 0, 0
curr_counter = Counter()
while r < len(s2):
if curr_counter == s1_count:
return True
while r - l + 1 > len(s1):
curr_counter[s2[l]] -= 1
l += 1
curr_counter[s2[r]] += 1
r += 1
return curr_counter == s1_count
# OR
from itertools import permutations
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
if len(s1) > len(s2):
return False
s1ctr, s2ctr = [0] * 26, [0] * 26
for i in range(len(s1)):
s1ctr[ord(s1[i]) - ord('a')] += 1
s2ctr[ord(s2[i]) - ord('a')] += 1
matches = 0
for i in range(26):
matches += (1 if s1ctr[i] == s2ctr[i] else 0)
l = 0
for r in range(len(s1), len(s2)):
if matches == 26:
return True
# for sliding the right end of the window
index = ord(s2[r]) - ord('a') #find what character has been added to window
s2ctr[index] += 1 #increment character's count in counter array
if s1ctr[index] == s2ctr[index]: #if frequencies same
matches += 1 #then matches++
elif s1ctr[index] + 1 == s2ctr[index]:#if frequency is increased in s2ctr after adding this new character
matches -= 1 #then matches--
# for sliding left end of window
index = ord(s2[l]) - ord('a') # find what character has been removed from window
s2ctr[index] -= 1 # decrement the character's count in counter array
if s1ctr[index] == s2ctr[index]: # if removing that character equals both counts
matches += 1 #mathces ++
elif s1ctr[index] - 1 == s2ctr[index]: #if frequency is decrased in s2ctr after removing from left
matches -= 1 #matches--
l += 1 #keep sliding the window
return matches == 26