题解 | #最小覆盖子串#

最小覆盖子串

https://www.nowcoder.com/practice/c466d480d20c4c7c9d322d12ca7955ac

class Solution:
    def minWindow(self , S: str, T: str) -> str:
        # 检查是否所有的元素都包含在滑动窗口内
        def check(hash):
            for _, val in hash.items():
                if val < 0:
                    return False
            return True

        left = 0
        right = 0
        res = ""
        hash = {}
        count = len(S)

        for i in range(len(T)):
            if T[i] in hash:
                hash[T[i]] -= 1
            else:
                hash[T[i]] = -1

        while right < len(S):
            if S[right] in hash:
                hash[S[right]] += 1

            while check(hash):
                if count > right-left:
                    count = right - left
					res= S[left:right+1]
                    
                if S[left] in hash:
                    hash[S[left]] -= 1
                
                left += 1
            right += 1

        return res

解题思路

  1. 先构建一个哈希表,让所有的元素的值为负数;
  2. 遍历S,如果当前值在哈希表内,则哈希表中的该元素的值加一;
  3. 并且判断滑动窗口是否包含了T中的所有元素,如果是的:
  • 当当前滑动窗口元素数count值大于right-left时,更新count值;
  • 并记录当前滑动窗口的内容。
  • 当左指针指向的元素在滑动窗口内时,将其哈希值减一。
  • 左指针往右移一位。

4. 右指针向右移一位。

5. 返回结果值。

全部评论

相关推荐

09-26 19:45
门头沟学院 Java
点赞 评论 收藏
分享
牛客小菜鸡66:boss里面,招人的叫老板,找工作的叫牛人
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务