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的字符后,然后再收缩头指针,直到不能再收缩为止。最后记录所有可能的情况中窗口最小的

    class Solution {
    public:
        string minWindow(string S, string T) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            vector<int> expect(256, 0);
            vector<int> appear(256, 0);
            int count = 0; 
            int start = 0;
            int minstart= 0;
            int minLen = INT_MAX;
            
            for(int i = 0; i < T.size(); i++)expect[T[i]]++;
            
            for(int  i = 0; i < S.size() ; i++)
            {
                if(expect[S[i]] > 0){
                    appear[S[i]]++;
                    if(appear[S[i]] <= expect[S[i]])
                        count++;
                }
                if(count == T.size()){
                    while(expect[S[start]] == 0 || appear[S[start]] > expect[S[start]]){
                        appear[S[start]]--;
                        start++;
                    }
                    if(minLen > (i - start +1) ){
                        minLen = i - start + 1 ;
                        minstart = start;
                    }
                }
            }
            
            if(minLen == INT_MAX) return string("");
            
            return S.substr(minstart, minLen);    
        }
    };
  • 相关阅读:
    堆模板
    二叉树输出
    中序+层次遍历输出前序
    扩展二叉树 (根据特殊的前序遍历建树)
    Leecode no.124 二叉树中的最大路径和
    JVM类加载过程
    Leecode no.208 实现Tire(前缀树)
    Leecode no.300 最长递增子序列
    volatile关键字深入解析 JMM与内存屏障
    Leecode no.200 岛屿数量
  • 原文地址:https://www.cnblogs.com/graph/p/3258676.html
Copyright © 2011-2022 走看看