北美程序员面试干货

LeetCode 76 [Minimum Window Subs

2016-08-07  本文已影响124人  Jason_Yuan

原题

给定一个字符串source和一个目标字符串target,在字符串source中找到包括所有目标字符串字母的子串。

说明在答案的子串中的字母在目标字符串中是否需要具有相同的顺序?
——不需要。

样例
给出source = "ADOBECODEBANC",target = "ABC" 满足要求的解 "BANC"

解题思路

完整代码

class Solution(object):
    def minWindow(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        if not s or not t or len(t) > len(s):
            return ""
        right, res = 0, []
        length = sys.maxint
        sourceHash, targetHash = {}, {}
        for char in t:
            if char not in targetHash:
                targetHash[char] = 1
            else:
                targetHash[char] += 1
                
        for left in range(len(s)):
            while not self.valid(sourceHash, targetHash) and right < len(s):
                if s[right] not in sourceHash:
                    sourceHash[s[right]] = 1
                else:
                    sourceHash[s[right]] += 1
                right += 1
            if self.valid(sourceHash, targetHash) and right - left< length:
                length = right - left
                res = [left, right]
            sourceHash[s[left]] -= 1
        
        return "" if not res else s[res[0]:res[1]]
        
    def valid(self, sourceHash, targetHash):
        for key, value in targetHash.items():
            if key not in sourceHash:
                return False
            elif key in sourceHash and targetHash[key] > sourceHash[key]:
                return False
        return True
上一篇 下一篇

猜你喜欢

热点阅读