567. 字符串的排列

给定两个字符串s1s2,写一个函数来判断 s2 是否包含 s1 的排列。

换句话说,第一个字符串的排列之一是第二个字符串的子串。

示例1:

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

示例2:

输入: s1= "ab" s2 = "eidboaoo"
输出: False

注意:

  • 输入的字符串只包含小写字母
  • 两个字符串的长度都在 [1, 10,000] 之间

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


完整代码

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        from collections import defaultdict
        left = 0
        length = len(s2)
        needCnt = len(s1)
        need = defaultdict(int)
        for c in s1:
            need[c] += 1
        
        for right in range(length):
            if need[s2[right]] > 0:
                needCnt -= 1
            need[s2[right]] -= 1
            if needCnt == 0:
                while need[s2[left]] != 0:
                    need[s2[left]] += 1
                    left += 1
                if right - left + 1 == len(s1):
                    return True   
                need[s2[left]] += 1
                needCnt += 1
                left += 1
        return False