Permutation in String
Permutation in String
Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.
In other words, return true if one of s1’s permutations is the substring of s2.
Example
Input: s1 = “ab”, s2 = “eidbaooo”
Output: true
Explanation: s2 contains one permutation of s1 (“ba”).
Approach 1:
Implementation:
from collections import Counter
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
if len(s1) > len(s2):
return False
dict_1 = Counter(s1)
matched = 0
required = len(dict_1)
for i in range(len(s2)):
if s2[i] in dict_1:
dict_1[s2[i]] -= 1
if dict_1[s2[i]] == 0:
matched += 1
if i >= len(s1) and s2[i - len(s1)] in dict_1:
if dict_1[s2[i - len(s1)]] == 0:
matched -= 1
dict_1[s2[i-len(s1)]] += 1
if matched == required:
return True
return False
Complexity Analysis:
Time Complexity: O(len(s1) + len(s2))
Space Complexity: O(len(s1)) for the hashmap created by the Counter
Reflection
I should really work hard on these questions:)