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
  • 相关阅读:
    C#:字符串(转载9)
    C# 数组(转载8)
    C#:可空类型(转载7)
    XD 05
    eclipse 快捷键 干货
    XD 04
    XD 03
    model, mapper, xml
    02 MyBatis & Druid
    注解 用到
  • 原文地址:https://www.cnblogs.com/superzrx/p/3354599.html
Copyright © 2011-2022 走看看