Leetcode 76: Minimum Window Substring

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 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.

 

 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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode76.Minimum Window Substring

LeetCode in Python 76. Minimum Window Substring

leetcode 76. Minimum Window Substring

Leetcode 76: Minimum Window Substring

leetcode 76-Minimum Window Substring(hard)

leetcode76 Minimum Window Substring