Skip to content

Commit 4b9a2d5

Browse files
author
Chris Cooper
committed
Refactor matches calculation to one-line.
We don't need l and r pointers, r is always l + len(s1).
1 parent 42a2695 commit 4b9a2d5

File tree

1 file changed

+13
-16
lines changed

1 file changed

+13
-16
lines changed

python/0567-permutation-in-string.py

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
class Solution:
2-
def checkInclusion(self, s1: str, s2: str) -> bool:
2+
def checkInclusion(self, s1, s2):
33
if len(s1) > len(s2):
44
return False
55

@@ -8,27 +8,24 @@ def checkInclusion(self, s1: str, s2: str) -> bool:
88
s1Count[ord(s1[i]) - ord("a")] += 1
99
s2Count[ord(s2[i]) - ord("a")] += 1
1010

11-
matches = 0
12-
for i in range(26):
13-
matches += 1 if s1Count[i] == s2Count[i] else 0
11+
matches = sum(map(lambda i: s1Count[i] == s2Count[i], range(26)))
1412

15-
l = 0
16-
for r in range(len(s1), len(s2)):
13+
for l in range(len(s2) - len(s1)):
1714
if matches == 26:
1815
return True
1916

20-
index = ord(s2[r]) - ord("a")
21-
s2Count[index] += 1
22-
if s1Count[index] == s2Count[index]:
17+
i = ord(s2[l]) - ord("a")
18+
s2Count[i] -= 1
19+
if s2Count[i] == s1Count[i]:
2320
matches += 1
24-
elif s1Count[index] + 1 == s2Count[index]:
21+
elif s2Count[i] == s1Count[i] - 1:
2522
matches -= 1
2623

27-
index = ord(s2[l]) - ord("a")
28-
s2Count[index] -= 1
29-
if s1Count[index] == s2Count[index]:
24+
i = ord(s2[l + len(s1)]) - ord("a")
25+
s2Count[i] += 1
26+
if s2Count[i] == s1Count[i]:
3027
matches += 1
31-
elif s1Count[index] - 1 == s2Count[index]:
28+
elif s2Count[i] == s1Count[i] + 1:
3229
matches -= 1
33-
l += 1
34-
return matches == 26
30+
31+
return matches == 26

0 commit comments

Comments
 (0)