zoukankan      html  css  js  c++  java
  • [LeetCode] 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 emtpy string "".

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

    双指针思想,尾指针不断往后扫,当扫到有一个窗口包含了所有T的字符,然后再收缩头指针,直到不能再收缩为止。最后记录所有可能的情况中窗口最小的

     1 class Solution {
     2 private:
     3     int count1[256];
     4     int count2[256];
     5 public:
     6     string minWindow(string S, string T) {
     7         // Start typing your C/C++ solution below
     8         // DO NOT write int main() function
     9         if (T.size() == 0 || S.size() == 0)
    10             return "";
    11             
    12         memset(count1, 0, sizeof(count1));
    13         memset(count2, 0, sizeof(count2));
    14         
    15         for(int i = 0; i < T.size(); i++)
    16         {
    17             count1[T[i]]++;
    18             count2[T[i]]++;
    19         }
    20         
    21         int count = T.size();
    22         
    23         int start = 0;
    24         int minSize = INT_MAX;
    25         int minStart;
    26         for(int end = 0; end < S.size(); end++)
    27         {
    28             if (count2[S[end]] > 0)
    29             {
    30                 count1[S[end]]--;
    31                 if (count1[S[end]] >= 0)
    32                     count--;
    33             }
    34             
    35             if (count == 0)
    36             {
    37                 while(true)
    38                 {
    39                     if (count2[S[start]] > 0)
    40                     {
    41                         if (count1[S[start]] < 0)
    42                             count1[S[start]]++;
    43                         else
    44                             break;
    45                     }
    46                     start++;
    47                 }
    48             
    49                 if (minSize > end - start + 1)
    50                 {
    51                     minSize = end - start + 1;
    52                     minStart = start;
    53                 }
    54             }
    55         }
    56         
    57         if (minSize == INT_MAX)
    58             return "";
    59         
    60         string ret(S, minStart, minSize);
    61         
    62         return ret;        
    63     }
    64 };
  • 相关阅读:
    Arrays类
    异常
    Java日志第53天 2020.8.29
    Java日志第52天 2020.8.28
    Java日志第55天 2020.8.31
    Java日志第54天 2020.8.30
    测试:ATM
    dear mother
    Spring
    People like me
  • 原文地址:https://www.cnblogs.com/chkkch/p/2774077.html
Copyright © 2011-2022 走看看