76. Minimum Window Substring

class Solution(object):
    def minWindow(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        #left, right pointers 
        # use dictionary as hash
        #positive and negative values represent in excess or in debt 
        l=len(s)
        min_len=float('inf')
        m_start=0
        hash_dict=collections.defaultdict(int)
        count=len(t) #count the number of char in t still unidentified in s 
        for ch in t: 
            hash_dict[ch]+=1
        left,right=0,0
        while right<l:
            if s[right] in hash_dict:
                #when meet a key char, record in hash,(negative value represent in excess) 
                #if it is one of what we are currently looking for(hash value>0), reduce count 
                if hash_dict[s[right]]>0:count-=1
                hash_dict[s[right]]-=1
            right+=1
            while count==0: 
                if min_len>right-left+1:#record the shorter solution if encounter one 
                    m_start=left
                    min_len=right-left+1
                if s[left] in hash_dict: 
                    #when we are to leave out one key char, register in hash
                    #only start looking for it on the right when hash value is positive 
                    hash_dict[s[left]]+=1
                    if hash_dict[s[left]]>0:count+=1 
                left+=1 
        if min_len==float('inf'): return ''
        return s[m_start:m_start+min_len-1]
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容