lintcode 32. Minimum Window Substring

32. Minimum Window Substring

Given a string source and a string target, find the minimum window in source which will contain all the characters in target.

Example

For source = "ADOBECODEBANC", target = "ABC", the minimum window is "BANC"

Idea:

一个字典存储target,另一个字典动态更新source字符。遍历target,遍历的每个元素为左边界,尝试找到满足条件有边界。如果找到就有结果。

Code

class Solution:
    """
    @param source : A string
    @param target: A string
    @return: A string denote the minimum window, return "" if there is no such a string
    
    一个字典存储target,另一个字典动态更新source字符。遍历target,遍历的每个元素为左边界,
尝试找到满足条件有边界。如果找到就有结果。
    """
    
    
    def minWindow(self, source , target):
        # write your code here
        if source is None:
            return ""
        
        targetHash = self.getTargetHash(target)
        targetUniqueChars = len(targetHash)
        matchedUniqueChars = 0
        
        hash = {}
        n = len(source)
        j = 0
        minLength = n + 1 
        minWindowString = "" 
        
        for i in range(n):
            while j < n and matchedUniqueChars < targetUniqueChars:
                if source[j] in targetHash: #找到字符
                    hash[source[j]] = hash.get(source[j], 0) + 1  #
                    if hash[source[j]] == targetHash[source[j]]:
                        matchedUniqueChars += 1 
                j += 1 
            
            if j - i < minLength and matchedUniqueChars == targetUniqueChars:
                minLength = j - i 
                minWindowString = source[i:j] 
            
            if source[i] in targetHash:
                if hash[source[i]] == targetHash[source[i]]:
                    matchedUniqueChars -= 1 
                hash[source[i]] -= 1 
        return minWindowString 
        
    def getTargetHash(self, target):
        hash = {}
        for c in target:
            hash[c] = hash.get(c, 0) + 1 
#dict.get(key[, default]) dict.get(key[,default]) 会查询字典中的key键,要是存在key键,则
#返回key键的值,要是没有key键,则返回 default, 若是没有 default,则返回 None。
        return hash         
                    
                    
            

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值