Skip to content

Commit 77ad2e8

Browse files
authored
Create permutation-in-string.py
1 parent 424de5b commit 77ad2e8

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Python/permutation-in-string.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
# Given two strings s1 and s2, write a function to return true
5+
# if s2 contains the permutation of s1. In other words,
6+
# one of the first string's permutations is the substring of the second string.
7+
#
8+
# Example 1:
9+
# Input:s1 = "ab" s2 = "eidbaooo"
10+
# Output:True
11+
# Explanation: s2 contains one permutation of s1 ("ba").
12+
# Example 2:
13+
# Input:s1= "ab" s2 = "eidboaoo"
14+
# Output: False
15+
# Note:
16+
# The input strings only contain lower case letters.
17+
# The length of both given strings is in range [1, 10,000].
18+
19+
class Solution(object):
20+
def checkInclusion(self, s1, s2):
21+
"""
22+
:type s1: str
23+
:type s2: str
24+
:rtype: bool
25+
"""
26+
counts = collections.Counter(s1)
27+
l = len(s1)
28+
for i in xrange(len(s2)):
29+
if counts[s2[i]] > 0:
30+
l -= 1
31+
counts[s2[i]] -= 1
32+
if l == 0:
33+
return True
34+
start = i + 1 - len(s1)
35+
if start >= 0:
36+
counts[s2[start]] += 1
37+
if counts[s2[start]] > 0:
38+
l += 1
39+
return False

0 commit comments

Comments
 (0)