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.

    class Solution {
    public:
        int sub(char c){
            if(c>='a'&&c<='z'){
                return c-'a';
            }
            else if(c>='A'&&c<='Z')
            {
                return c-'A'+26;
            }
            else return -1;
        }
        string minWindow(string S, string T) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            vector<int> count,count2;
            count.resize(52,0);
            count2.resize(52,0);
            for(int i=0;i<T.length();i++){
                int ind=sub(T[i]);
                if(ind!=-1)count[ind]++;
            }
            int dis=0;
            for(int i=0;i<52;i++){
                dis+=count[i];
            }
            int mins=-1,mine;
            int start=0,end=0;
            int ind=sub(S[end]);
            if(ind!=-1){
                count2[ind]++;
                if(count2[ind]<=count[ind])dis--;
            }
            while(true){
                if(dis!=0){
                    end++;
                    if(end==S.length())break;
                    int ind=sub(S[end]);
                    if(ind!=-1){
                        count2[ind]++;
                        if(count2[ind]<=count[ind])dis--;
                    }
                }
                else{
                    if(mins==-1||end-start<mine-mins){
                        mins=start;
                        mine=end;
                    }
                    int ind=sub(S[start]);
                    if(ind!=-1){
                        count2[ind]--;
                        if(count2[ind]<count[ind]){
                            dis++;
                        }
                    }
                    start++;
                    if(start>end)break;
                }
            }
            if(mins==-1)return "";
            return S.substr(mins,mine-mins+1);
        }
    };
    View Code
  • 相关阅读:
    HTTPS协议详解
    HTTP协议详解
    网络传输协议 UDP & TCP 详解
    Socket(套接字)基础概念
    网络基础
    OSI 七层协议
    经典SQL题 1/25/50/100美分,多少种可能拼凑成2美元
    5.1一阶谓词逻辑
    4.4符号视角下的科学
    4.3领域语言与自然语言的比较
  • 原文地址:https://www.cnblogs.com/superzrx/p/3354599.html
Copyright © 2011-2022 走看看