1. 程式人生 > >LeetCode76.Minimum Window Substring

LeetCode76.Minimum Window Substring

大小 com pre min span ant eba mis 方案

題目:

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.

思路:

題目要求的時間復雜度為O(n),意味著選定窗口大小,依次遍歷字符串的暴力方法(時間復雜度為O(n^2))不合適。

聯想到“有序數組和中為S的兩個數”問題的解法,可以嘗試用指針移動的方式來遍歷字符串,以達到O(n)的時間復雜度。

基本的思路是右指針從左向右遍歷S,對每一個右指針問題,求可能的最短窗口(用左指針從左向右的遍歷實現)。為了判斷窗口的合法性,需要一個字典,存儲目標字符串T中的元素在窗口中是否出現。

python的具體實現代碼如下:

 1 class Solution(object):
 2     def minWindow(self, s, t):
 3         if
not s or not t: 4 return "" 5 need = {} 6 for char in t: 7 if char not in need: 8 need[char] = 1 9 else: 10 need[char] += 1 11 missing = len(t) 12 min_left = 0 13 min_len = len(s) + 1 14 left = 0
15 for right, char in enumerate(s): 16 if char in need: 17 need[char] -= 1 18 if need[char] >= 0: 19 missing -= 1 20 while missing == 0: 21 if right - left + 1 < min_len: 22 min_left, min_len = left, (right - left + 1) 23 if s[left] in need: 24 need[s[left]] += 1 25 if need[s[left]] > 0: 26 missing += 1 27 left += 1 28 if min_len > len(s): 29 return "" 30 return s[min_left: min_left + min_len]

在leetcode上顯示運行時間快過99%的提交方案

技術分享圖片

LeetCode76.Minimum Window Substring