Leetcode練習(Python):哈希表類:第76題:最小覆蓋子串:給你一個字符串 S、一個字符串 T,請在字符串 S 里面找出:包含 T 所有字母的最小子串。


題目:
最小覆蓋子串:給你一個字符串 S、一個字符串 T,請在字符串 S 里面找出:包含 T 所有字母的最小子串。

說明:

  • 如果 S 中不存這樣的子串,則返回空字符串 ""
  • 如果 S 中存在這樣的子串,我們保證它是唯一的答案。
思路:
使用滑動窗口法。
程序:
from collections import defaultdict
class Solution:
    def minWindow(self, s: 'str', t: 'str') -> 'str':
        if not s or not t:
            return ""
        findOut = defaultdict(int)
        for letter in t:
            findOut[letter] += 1
        index1 = 0
        index2 = 0
        counter = len(t)
        length = len(s)
        min_len = float("inf")
        result = ""
        while index2 < length:
            if findOut[s[index2]] >= 1:
                counter -= 1
            findOut[s[index2]] -= 1
            index2 += 1
            while counter == 0:
                if min_len > index2 - index1:
                    min_len = index2 - index1
                    result = s[index1 : index2]
                if findOut[s[index1]] == 0:
                    counter += 1
                findOut[s[index1]] += 1
                index1 += 1
        return result


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM