Python版-LeetCode 学习:567. 字符串的排列

给定两个字符串 s1 和 s2,写一个函数来判断 s2 是否包含 s1 的排列。换句话说,第一个字符串的排列之一是第二个字符串的子串。

示例1:   输入: s1 = "ab" s2 = "eidbaooo"    输出: True
解释: s2 包含 s1 的排列之一 ("ba").
示例2:   输入: s1= "ab" s2 = "eidboaoo"     输出: False

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutation-in-string

该题同 “438. 找到字符串中所有字母异位词”解法极其类似

方法1:都是利用滑动窗口,将滑动窗口中的字符与s1中的字符串进行比对,如果相同则认为

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        if len(s1)>len(s2): return False
        record=Counter(s1)
        length=len(s1)

        win={}
        l=0
        rst=False   # 不同处
        for r,c in enumerate(s2):
            if c not in record.keys():
                win.clear()
                l=r+1
            else:
                win[c]=win.get(c,0)+1
                if r-l+1==length:
                    if win==record:
                        rst=True    # 不同处
                    win[s2[l]]-=1
                    l+=1
        return rst

方法2:方法1的变种

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        if len(s1) > len(s2):
           return False
        need = {}
        window = {}
        for i in s1:
            if i in need:
                need[i] += 1
            else:
                need[i] = 1
        print(need,len(need))
        left = 0
        right = 0
        valid = 0
        while right < len(s2):
            c = s2[right]
            right += 1
            if c in need:
                # 窗口开始,在不在need和window中
                if c in window:
                    window[c] += 1
                else:
                    window[c] = 1
                # 判断窗口函数值是否相同,相同则标记加1
                if window[c] == need[c]:
                    valid += 1
            if right - left >= len(s1):
                # 当窗口长度大于目标字符串长度时
                # 若valid等于字典need的长度时,即所有字符都比对完成时,还回 true
                if valid == len(need):
                    return True
                # 移动左边界,把最左边的字符清除出window
                d = s2[left]
                left += 1
                if d in need:
                    # 如果这时需要清除的字符d在字典need中,则需要处理标记值valid和窗口值
                    if window[d] == need[d]:
                        valid -= 1
                    window[d] -= 1
        return False

猜你喜欢

转载自blog.csdn.net/guyu1003/article/details/107418702