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 };
  • 相关阅读:
    团队作业
    第四次作业
    第三次作业
    从电梯问题,看c和c++之间的区别(有点懂了)错觉错觉
    团队作业2
    游戏方案
    电梯调度程序4
    电梯调度程序3
    电梯调度程序2
    电梯调度程序1
  • 原文地址:https://www.cnblogs.com/chkkch/p/2774077.html
Copyright © 2011-2022 走看看