1. 程式人生 > >[Swift]LeetCode76. 最小覆蓋子串 | Minimum Window Substring

[Swift]LeetCode76. 最小覆蓋子串 | 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).

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.

 給定一個字串 S 和一個字串 T,請在 S 中找出包含 T 所有字母的最小子串。

示例:

輸入: S = "ADOBECODEBANC", T = "ABC"
輸出: "BANC"

說明:

  • 如果 S 中不存這樣的子串,則返回空字串 ""
  • 如果 S 中存在這樣的子串,我們保證它是唯一的答案。

超出時間限制

 1 class Solution {
 2     func minWindow(_ s: String, _ t: String) -> String {
 3         if t.count > s.count {return String()} 
 4         var res:String = String()
 5         var left = 0, count = 0, minLen = s.count + 1
 6         var tm:[Int] = [Int](repeating:0
,count: 128) 7 var sm:[Int] = [Int](repeating:0,count: 128) 8 for i in 0..<t.count 9 { 10 tm[t[i]] += 1 11 } 12 for right in 0..<s.count 13 { 14 let numRight = s[right] 15 if tm[numRight] != 0 16 { 17 sm[numRight] += 1 18 if sm[numRight] <= tm[numRight] 19 { 20 count += 1 21 } 22 while (count == t.count) 23 { 24 if right - left + 1 < minLen 25 { 26 minLen = right - left + 1 27 res = s.subString(left, minLen) 28 } 29 let numLeft = s[left] 30 if tm[numLeft] != 0 31 { 32 sm[numLeft] -= 1 33 if sm[numLeft] < tm[numLeft] 34 { 35 count -= 1 36 } 37 } 38 left += 1 39 } 40 } 41 } 42 return res 43 } 44 } 45 46 extension String { 47 48 //subscript函式可以檢索陣列中的值 49 //按照索引方式讀取字元 50 subscript (_ num: Int) -> Int { 51 //讀取字元 52 get 53 { 54 let s = String(self[index(self.startIndex,offsetBy: num)]).unicodeScalars 55 return Int(s[s.startIndex].value) 56 } 57 } 58 59 // 擷取字串:指定索引和字元數 60 // - begin: 開始擷取處索引 61 // - count: 擷取的字元數量 62 func subString(_ begin:Int,_ count:Int) -> String { 63 let start = self.index(self.startIndex, offsetBy: max(0, begin)) 64 let end = self.index(self.startIndex, offsetBy: min(self.count, begin + count)) 65 return String(self[start..<end]) 66 } 67 }