力扣567. 字符串的排列

143 阅读1分钟

1. 题目

leetcode.cn/problems/pe…

image.png

2. 题解

采用滑动窗口解法

3. 核心代码

-> 滑动窗口方法

import collections


class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        need = collections.Counter(s1)
        window = {}
        left = right = 0
        valid = 0
        while right < len(s2):
            c = s2[right]
            right += 1
            if c in s1:
                window[c] = window.get(c, 0) + 1
                if window[c] == need[c]:
                    valid += 1
            while valid == len(need):
                if right - left == len(s1):
                    return True
                d = s2[left]
                left += 1
                if d in s1:
                    if window[d] == need[d]:
                        valid -= 1
                    window[d] -= 1
        return False


if __name__ == '__main__':
    s = Solution()
    print(s.checkInclusion('ab', "eidboaoo"))

-> 取巧法

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        lst1 = [0] * 26
        lst2 = [0] * 26
        if len(s1) > len(s2):
            return False
        for i in range(len(s1)):
            lst1[ord(s1[i]) - 97] += 1
            lst2[ord(s2[i]) - 97] += 1
        if lst1 == lst2:
            return True
        for j in range(len(s2) - len(s1)):
            lst2[ord(s2[j + len(s1)]) - 97] += 1
            lst2[ord(s2[j]) - 97] -= 1
            if lst1 == lst2:
                return True
        return False