Permutation in String

Intuition

The problem involves checking if one of the permutations of string s1 is a substring of string s2. The solution needs to efficiently handle the changing window of length w in string s2 and determine if, at any point, the characters in the window form a permutation of s1.

Approach

The provided solution uses a sliding window approach along with a dictionary (dic) to keep track of the counts of characters in the current window.

Initialize the dictionary dic to store the counts of characters in s1.
Initialize the variable s1count to 1, representing the count of characters in s1.
Iterate through each character in s1 and update the counts in the dictionary.
Iterate through the characters in s2 using the variable i ranging from 0 to len(s2) - 1:
If the current character in s2 is in the dictionary, decrement its count.
If the index i is greater than or equal to the length of s1, increment the count of the character at position i - w if it is in the dictionary.
Check if all values in the dictionary are zero. If true, return True because a permutation of s1 is found in the current window.
If no permutation is found in any window, return False.

Complexity

  • Time complexity:

The time complexity of this solution is O(n + n), where len(s1) is the length of string s1 and len(s2) is the length of string s2. The solution iterates through both strings once.

  • Space complexity:

The space complexity is O(n), as the dictionary dic stores the counts of characters in s1. The space used is proportional to the size of s1.

Code

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        dic = {}
        s1count = 1
        w = len(s1)
        length = range(len(s2))
        for s in s1:
            if s in dic:
                dic[s] += 1
            else:
                dic[s] = s1count

        for i in length:
            if s2[i] in dic:
                dic[s2[i]] -= 1
                
            if i >= w and s2[i-w] in dic:
                dic[s2[i-w]] += 1
            
            if all(val == 0 for val in dic.values()):
                return True

        return False
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值