固定窗口
示例
假设有一个数组 nums = [1, 3, -1, -3, 5, 3, 6, 7]
,我们需要找到长度为 3 的最大子数组之和。
nums = [1, 3, -1, -3, 5, 3, 6, 7]
window_size = 3
max_sum = float('-inf')
for i in range(len(nums) - window_size + 1):
current_sum = sum(nums[i:i + window_size])
max_sum = max(max_sum, current_sum)
print(max_sum) # 输出: 13 (5 + 3 + 6)
变长窗口
示例
假设有一个字符串 s = "abcde"
,我们需要找到包含所有不同字符的最短子串。
from collections import defaultdict
def min_substring_length(s):
char_count = defaultdict(int)
required_chars = len(set(s))
left, right = 0, 0
min_length = float('inf')
formed_chars = 0
while right < len(s):
char_count[s[right]] += 1
if char_count[s[right]] == 1:
formed_chars += 1
while left <= right and formed_chars == required_chars:
min_length = min(min_length, right - left + 1)
char_count[s[left]] -= 1
if char_count[s[left]] == 0:
formed_chars -= 1
left += 1
right += 1
return min_length if min_length != float('inf') else 0
s = "abcde"
print(min_substring_length(s)) # 输出: 5
这种方法通常比暴力搜索方法更高效,因为它避免了不必要的重复计算。