标签:unique length string dict i++ guarantee public nbsp cti
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.
1 public class Solution { 2 public string MinWindow(string s, string t) { 3 if (s == "" || t == "") return ""; 4 5 var dict = new Dictionary<char, int>(); 6 7 for (int i = 0; i < t.Length; i++) 8 { 9 if (dict.ContainsKey(t[i])) 10 { 11 dict[t[i]]++; 12 } 13 else 14 { 15 dict[t[i]] = 1; 16 } 17 } 18 19 int start = 0, j = 0, count = t.Length; 20 var result = ""; 21 22 while (j < s.Length) 23 { 24 if (dict.ContainsKey(s[j])) 25 { 26 if (dict[s[j]] > 0) 27 { 28 count--; 29 } 30 31 dict[s[j]]--; 32 } 33 34 while (count == 0 && start <= j) 35 { 36 if (result == "" || result.Length > j - start + 1) 37 { 38 result = s.Substring(start, j - start + 1); 39 } 40 41 if (dict.ContainsKey(s[start])) 42 { 43 dict[s[start]]++; 44 45 if (dict[s[start]] > 0) 46 { 47 count++; 48 } 49 } 50 51 start++; 52 } 53 54 j++; 55 } 56 57 return result; 58 } 59 }
Leetcode 76: Minimum Window Substring
标签:unique length string dict i++ guarantee public nbsp cti
原文地址:http://www.cnblogs.com/liangmou/p/7818058.html