[2025-09-27] Leetcode 76. 最小覆盖子串

题目

76. 最小覆盖子串
给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 “” 。
 
注意:

  • 对于 t 中重复字符,我们寻找的子字符串中该字符数量必须不少于 t 中该字符数量。
  • 如果 s 中存在这样的子串,我们保证它是唯一的答案。
     
    示例 1:
    输入:s = “ADOBECODEBANC”, t = “ABC”
    输出:”BANC”
    解释:最小覆盖子串 “BANC” 包含来自字符串 t 的 ‘A’、’B’ 和 ‘C’。
    示例 2:
    输入:s = “a”, t = “a”
    输出:”a”
    解释:整个字符串 s 是最小覆盖子串。
    示例 3:
    输入: s = “a”, t = “aa”
    输出: “”
    解释: t 中两个字符 ‘a’ 均应包含在 s 的子串中,
    因此没有符合条件的子字符串,返回空字符串。
     
    提示:
  • m == s.length
  • n == t.length
  • 1 <= m, n <= 105
  • s 和 t 由英文字母组成
     
    进阶:你能设计一个在 o(m+n) 时间内解决此问题的算法吗?

我的代码(Python)

class Solution:
    def minWindow(self, s: str, t: str) -> str:
        tDict = {}
        for c in t:
            if c in tDict:
                tDict[c] += 1
            else:
                tDict[c] = 1
        count = len(tDict)
        currCnt = 0
        startIdx = -1
        currResult = ''
        currDict = {}
        for i in range(len(s)):
            if s[i] in tDict:
                if startIdx == -1:
                    startIdx = i
                if s[i] in currDict:
                    currDict[s[i]] += 1
                else:
                    currDict[s[i]] = 1
                if currDict[s[i]] == tDict[s[i]]:
                    currCnt += 1
                if currCnt == count:
                    if not currResult or i + 1 - startIdx < len(currResult):
                        currResult = s[startIdx: i+1]
                    while startIdx <= i:
                        if s[startIdx] not in tDict:
                            startIdx += 1
                            continue
                        if currCnt < count:
                            break
                        if currCnt == count and i + 1 - startIdx < len(currResult):
                            currResult = s[startIdx: i+1]
                        if s[startIdx] in currDict:
                            currDict[s[startIdx]] -= 1
                            if currDict[s[startIdx]] == tDict[s[startIdx]] - 1:
                                currCnt -= 1
                        startIdx += 1
                    if startIdx > len(s) - len(t):
                        break
                    if startIdx > i:
                        startIdx = -1
        return currResult

点评

时间和空间上都处于中等。思路和官方是一样的,滑动窗口,先向后扩展到覆盖子串,再收缩前方的索引到最小。
官方没有给出Python代码,我的代码看起来很啰嗦,应该还有优化空间。
根据官方的思路,可以用一个队列或者双向队列存储在子串中的字母的索引,这样收缩的时候可以直接跳到这个值,不用再次判断是否在子串中,应该可以继续优化。

发表评论

您的邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部