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 };
  • 相关阅读:
    csu 1547(01背包)
    csu 1592(区间DP)
    Funny Car Racing(最短路变形)
    csu 1329 一行盒子(链表操作)
    poj 2828(线段树单点更新)
    软件开发文档模板 (学习)
    C 语言高效编程与代码优化
    【整理】uclibc,eglibc,glibc之间的区别和联系
    查找openssl内存泄漏(代码)
    openssl内存分配,查看内存泄露
  • 原文地址:https://www.cnblogs.com/chkkch/p/2774077.html
Copyright © 2011-2022 走看看