• 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
  • 相关阅读:
    岛田庄司《占星术杀人魔法》读后感
    OutputCache祥解
    ZOJ Monthly, June 2014 月赛BCDEFGH题题解
    接口和抽象类有什么差别
    C语言指针的初始化和赋值
    深入探讨this指针
    郁 繁体为“鬰” 古同 “鬱”
    socketpair的使用
    Android的FrameLayout使用要注意的问题
    下确界和上确界
  • 原文地址:https://www.cnblogs.com/superzrx/p/3354599.html
Copyright © 2020-2023  润新知