Python滑动窗口算法核心逻辑与适用场景解析

Finn
Finn
发布时间:2026-12-05| 905人浏览过
原创

使用两个指针维护区间,通过移动右指针扩展窗口、左指针收缩窗口来统计目标子串或子数组信息。

Python滑动窗口算法核心逻辑与适用场景解析

滑动窗口的核心结构与适用场景

滑动窗口适用于连续子序列问题,如最长无重复字符子串、最小覆盖子串等。其核心在于动态调整窗口大小以满足条件。

Python滑动窗口算法核心逻辑与适用场景解析

适用场景: - 连续子数组/子串 - 需要满足特定条件的最值或计数 - 数据流中的实时统计

不适用场景: - 非连续元素组合 - 需要全局排序的问题

Python实现最小覆盖子串

以下代码实现了寻找字符串s中包含t所有字符的最小子串。将代码保存为sliding_window.py并运行即可看到结果。

Python滑动窗口算法核心逻辑与适用场景解析

def min_window(s: str, t: str) -> str:
    if not s or not t:
        return ""
    
    from collections import defaultdict
    
    target_count = defaultdict(int)
    for char in t:
        target_count[char] += 1
    
    required = len(target_count)
    left = 0
    right = 0
    formed = 0
    window_counts = defaultdict(int)
    
    ans_left = -1
    ans_right = float('inf')
    
    while right < len(s):
        char = s[right]
        window_counts[char] += 1
        
        if char in target_count and window_counts[char] == target_count[char]:
            formed += 1
        
        while left <= right and formed == required:
            char = s[left]
            
            if right - left + 1 < ans_right - ans_left + 1:
                ans_left = left
                ans_right = right
            
            window_counts[char] -= 1
            if char in target_count and window_counts[char] < target_count[char]:
                formed -= 1
            
            left += 1
        
        right += 1
    
    return "" if ans_left == -1 else s[ans_left:ans_right + 1]

# 示例调用
print(min_window("ADOBECODEBANC", "ABC"))  # 输出: "BANC"

程序输出为最短包含t所有字符的子串。若输入变化导致无解,则返回空字符串。排错时可检查target_count初始化及formed更新逻辑。

该实现使用哈希表记录字符需求,通过左右指针动态调整窗口。

处理空输入与边界情况

当输入字符串为空或t包含s中不存在的字符时,程序应返回空字符串或适当提示。

在实际应用中,需确保输入合法性检查,避免索引越界或逻辑错误。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Python

Python

3.15.0 · Windows

Python 官方解释器与标准库,适合 Python 学习和应用开发。

Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。