February-567. Permutation of strings

 

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        if not s1 and not s2:
            return True
        
        if not s1 or not s2:
            return False
    
        #计算s1和s2的长度
        l1,l2 = len(s1),len(s2)

        #对s1中的各个元素进行Counter计算
        c1 = Counter(s1)
        c2 = Counter()
        l,r = 0,0

        while r<l2:
            #如果新元素没出现在字典中,进行更新
            c2[s2[r]]+=1
            #如果在窗口大小为l1的数组中,两个hash表相同,则返回True
            if c1==c2:
                return True
            #移动右指针
            r+=1

            #维护一个大小为l1的窗口
            if r-l+1>l1:
                #左移的话,字典计算减1
                c2[s2[l]]-=1
                #如果计算减1之后为0,则删掉c2字典中的元素
                #因为{'a':0,'b':1}!={'b':1}
                if c2[s2[l]]==0:
                    del c2[s2[l]]
            #同时移动左右指针
                l+=1
        return  False
  • First judge whether it is empty, if it is not empty, then use the sliding window method to do it
  • Idea: Maintain a sliding window with the same size as s1, and then judge whether the number of characters appearing in this window is the same. If they are the same, it means that s2 contains s1.
    • First declare two dictionaries, one dictionary is calculated by s1, and an empty dictionary is used to count the elements in s2
    • First update the c2 dictionary, and then judge whether the two dictionaries are the same, if they are different, move the right pointer
    • Then determine if the current window is greater than l1, if so, move it to the left by one unit, and subtract the count in the dictionary
    • If it is not satisfied in the while loop, it means that s2 does not contain s1, just return False directly.

#The last brush before

Guess you like

Origin blog.csdn.net/weixin_37724529/article/details/113780567