76. Minimum Window Substring

本文深入探讨了滑动窗口算法的原理及应用,包括基本滑动窗口与变体滑动窗口的概念,通过具体实例解析了如何求解字符串中最小子串问题,展示了算法的设计思路与实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

tags: Hash Table, Two Pointers, String difficulty: Hard

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

Example:

Input: S = "ADOBECODEBANC", T = "ABC"  
Output: "BANC"  

Note:

If there is no such window in S that covers all characters in T, return the empty string "".
If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

Solution
  1. 创建一个包含所有T中字节的窗口
  2. 从左侧减小窗口大小,如果符合条件(包含所有T中字节),记录最小长度与起止位置
  3. 如果不符合条件,从右侧扩大窗口,使之符合条件
  4. 重复2、 3直到 S 最末端
func minWindow(s string, t string) string {
    if len(s) == 0 || len(t) == 0 {
        return ""
    }
    mapT := make([]int, 256)
    for i:=0;i<len(t);i++{
        mapT[int(t[i])]+=1
    }
    posPair := []int{-1,-1}
    counter := len(t)
    minWin := len(s)
    
    start :=0
    
    for index,val := range s{
        mapT[int(val)] -=1
        if mapT[int(val)] >= 0{
            counter--
        }
        
        for ;counter==0;start++ {
            if minWin > index - start {
                posPair[0] = start
                posPair[1] = index
                minWin = index - start
            }
            mapT[int(s[start])]+=1
            if mapT[int(s[start])] > 0 {
                counter++
            }
        }
    }
    if posPair[0] == -1 {
        return ""
    }
    return s[posPair[0]:posPair[1]+1]
}

这是一个滑动窗口的算法题,基本的滑动窗口算法窗口大小是固定的,本题是滑动窗口的一个变体应用。

基本滑动窗口

可以查看Window Sliding Technique

应用方向:求连续大小为K的子数组的最大最小的值,和,积,xor 等

例子:Given an array of integers of size ‘n’. Our aim is to calculate the maximum sum of ‘k’ consecutive elements in the array.

变体滑动窗口

基本滑动窗口大小是固定的,而一般滑动窗口的大小是需要我们自己计算的,本题就是一例,根据网友的总结10-line template that can solve most 'substring' problems, 很多的子字符串类题都可以使用这种方法。

转载于:https://my.oschina.net/liufq/blog/2248871

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值