【Leetcode】76. Minimum Window Substring

class Solution1(object):
    def minWindow(self, s, t):
        """
        use a dict to store the count of d each character of t, we use the value of dict to represent how many character current string surplus for t
        if values less than 0, it's means the character is redundant, so we can jump it and add one to the value
        use two pointer left and right to identify current string
        we first scan from left to right and get index which s[:index+1] contains t
        the move right pointer one step at a time, after that, we move left pointer, if dict[s[left]] < 0, we jump it until dict[s[left]] > 0
        """
        from collections import defaultdict
        dict_t =  defaultdict(int)
        for char in t:
            dict_t[char] += 1
        count = len(t)
        index = 0
        for i in range(len(s)):
            if dict_t[s[i]] > 0:
                dict_t[s[i]] -= 1
                count -= 1
                if count == 0:
                    index = i
                    break
            else:
                dict_t[s[i]] -= 1
        if count > 0: return ""
        left, right = 0, index
        result = s[left: right+1]
        while(True):
            while(dict_t[s[left]] < 0):
                dict_t[s[left]] += 1
                left += 1
            if len(result) > right - left + 1:
                result = s[left:right+1]
            right += 1
            if right == len(s):
                break
            dict_t[s[right]] -= 1
        return result


class Solution2(object):
    """
    a little optimization of solution 1
    we only need to store character appear in t
    """
    def minWindow(self, s, t):
        dict_t = {}
        for char in t:
            dict_t[char] = dict_t.get(char, 0) + 1
        count = len(t)
        index = -1
        for i in range(len(s)):
            if s[i] in dict_t:
                if dict_t[s[i]] > 0:
                    count -= 1
                dict_t[s[i]] -=1
                if count == 0:
                    index = i
                    break
        if count > 0: return ""
        left, right, result  = 0, index, s[0:index+1]
        while(True):
            while(s[left] not in dict_t or dict_t[s[left]] < 0):
                if s[left] in dict_t:
                    dict_t[s[left]] += 1
                left += 1
            if len(result) > right - left + 1:
                result = s[left:right+1]
            right += 1
            if right == len(s):
                break
            if s[right] in dict_t:
                dict_t[s[right]] -= 1
        return result

相关文章: