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.

    思考:虽然也想到了时间换空间的方法,但是时间复杂度还是不能压到O(n)。我的思路是二维数组记录T中每个字符的index,然后转化为一个求最短距离。

    参考:http://discuss.leetcode.com/questions/97/minimum-window-substring

    此方法的精妙之处在于count!

    class Solution {
    public:
        string minWindow(string S, string T) {
            int p1[256]={0}; //need to find
            int p2[256]={0}; //has found
            int count=0; 
            int len1=S.size();
            int len2=T.size();
            for(int i=0;i<len2;i++) p1[T[i]]++;
            int start=0,end=0;
            int len=INT_MAX; //window大小
            int pos=-1;
            for(;end<len1;end++)
            {
                if(p1[S[end]]==0) continue; //S[end]不在T中,跳过
                p2[S[end]]++;
                if(p2[S[end]]<=p1[S[end]]) count++;
                if(count==len2) //找到一个window
                {
                    while(p1[S[start]]==0||p2[S[start]]>p1[S[start]]) 
                    {
                        if(p2[S[start]]>p1[S[start]]) p2[S[start]]--;
                        start++;
                    }
                    if(len>end-start+1) 
                    {
                        len=end-start+1;
                        pos=start;
                    }
                }
            }
            return (pos==-1)?"":S.substr(pos,len);
        }
    };
    

      

  • 相关阅读:
    mysql面试知识点
    计算机网络
    BFS
    拓扑排序
    双指针
    回溯算法
    hash表 算法模板和相关题目
    桶排序及其应用
    滑动窗口
    贪心算法
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3519884.html
Copyright © 2011-2022 走看看