• [Leetcode] Two pointer-- 76. Minimum Window Substring


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

    For example,
    S = "ADOBECODEBANC"
    T = "ABC"

    Minimum window is "BANC".

    Note:
    If there is no such window in S that covers all characters in T, return the empty string "".

    If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

    Solution:

    windows problem: use two pointer, fix left and move right pointer, traverse source s and find the current windows containing t,
    then move the left point to next point to update the current window length to get the minimum window

     1 targetHash = {}         #store the target character counter     
     2         
     3         for c in t:
     4             if c not in targetHash:
     5                 targetHash[c] = 1
     6             else:
     7                 targetHash[c] += 1
     8         
     9         srcHash = {}
    10         
    11         count = 0         #decide when T matched in S
    12         left = 0
    13         right = 0
    14         minWindLen = 2**32
    15         minStart = 0
    16         
    17         #print ("target hash: ", targetHash)
    18         while (right < len(s)):
    19             
    20             if s[right] in targetHash and targetHash[s[right]] > 0:
    21                 if s[right] not in srcHash:
    22                     srcHash[s[right]] = 1
    23                 else:
    24                      srcHash[s[right]] += 1
    25                 if (srcHash[s[right]] <= targetHash[s[right]]):
    26                     count += 1
    27             
    28             if count == len(t):
    29                     
    30                 
    31                 while (s[left] not in targetHash  or (s[left] in srcHash and s[left] in targetHash and srcHash[s[left]] > targetHash[s[left]])):
    32                     if s[left] in targetHash:
    33                         srcHash[s[left]] -= 1
    34                     left += 1
    35                     
    36                 if minWindLen > (right-left+1):
    37                     minWindLen = right-left+1
    38                     minStart = left
    39                                 
    40             
    41             right += 1
    42                 
    43         return s[minStart: minStart+minWindLen] if minWindLen <= len(s) else ""
  • 相关阅读:
    JSAJAX请求
    ES6-形参默认值
    ES6-三点运算符
    ES6-箭头函数
    ES6-对象的简写方式
    ES6-使用模板字符串完成字符串拼接
    201712-2 游戏
    Product of Polynomials
    Maximum Subsequence Sum
    蓝桥杯 龟兔赛跑预测
  • 原文地址:https://www.cnblogs.com/anxin6699/p/8249733.html
Copyright © 2020-2023  润新知