滑动窗口

  1. 固定长度
    解释:窗口的长度固定

    例题:

    给定一个字符串s,要求找到这个字符串的k位子串,要求这个子串里面,字符x的出现次数最多。返回出现次数

    def test(strs, num, char):
     length = len(strs)
     temp = 0
     res = 0
     for i in range(num - 1):
         if strs[i] == char:
             temp += 1
     # length - num 是窗口左指针可遍历的范围
     for j in range(length - num):
         right = j + num - 1
         if strs[right] == char:
             temp += 1
         #  j = 0 时不执行, 每次窗口右移时会判断是否需要减去窗口左边移出的值
         if j - 1 >= 0 and strs[j - 1] == char:
             temp -= 1
         if temp > res:
             res = temp
     return res
  2. 可变长度
    解释:窗口的长度可变
    例题: leetcode 题3

    给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

    class Solution:
     def lengthOfLongestSubstring(self, s: str) -> int:
         cur_length = 0
         max_length = 0
         temp = []
         left = 0
         length = len(s)
         for i in range(length):
             while s[i] in temp:
                 temp.remove(s[left])
                 left += 1
                 cur_length -= 1
             cur_length += 1
             temp.append(s[i])
             if cur_length > max_length:
                 max_length = cur_length
         return max_length