76. Minimum Window Substring

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:code

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

Note:blog

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.ip

Solution

  1. 建立一個包含全部T中字節的窗口
  2. 從左側減少窗口大小,若是符合條件(包含全部T中字節),記錄最小長度與起止位置
  3. 若是不符合條件,從右側擴大窗口,使之符合條件
  4. 重複二、 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]
}

這是一個滑動窗口的算法題,基本的滑動窗口算法窗口大小是固定的,本題是滑動窗口的一個變體應用。element

基本滑動窗口

能夠查看Window Sliding Techniqueleetcode

應用方向:求連續大小爲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.get

變體滑動窗口

基本滑動窗口大小是固定的,而通常滑動窗口的大小是須要咱們本身計算的,本題就是一例,根據網友的總結10-line template that can solve most 'substring' problems, 不少的子字符串類題均可以使用這種方法。string

相關文章
相關標籤/搜索