LeetCodeDiary

A Diary for solving LeetCode problems

View on GitHub
'''
Description: 
Autor: Au3C2
Date: 2020-12-14 15:10:00
LastEditors: Au3C2
LastEditTime: 2020-12-14 15:12:21
'''
class Solution:
    def shortestSeq(self, big: List[int], small: List[int]) -> List[int]:
        need = collections.Counter(small)
        needCnt = n_s = len(small)
        i = 0
        res = (0, len(big)+1)
        for j,c in enumerate(big):
            if need[c] > 0:
                needCnt -= 1    # 不在t中的字符默认是0,所以大于零的一定是t里的字符
            need[c] -= 1        # 当c出现次数超过所需次数时,need[c]<0,所以needcnt不会小于0
            if needCnt == 0:    # 步骤一:滑动窗口包含了所有T元素
                while True:     # 步骤二:增加i,排除多余元素
                    c = big[i] 
                    if need[c] == 0:
                        break
                    need[c] += 1
                    i += 1
                if j-i < res[1]-res[0]:   #记录结果
                    res =[i,j]
                    if j - i == n_s:
                        return res
                need[big[i]] += 1  #步骤三:i增加一个位置,寻找新的满足条件滑动窗口
                needCnt += 1
                i += 1
        return [] if res[1] > len(big) else res
# 和0076.最小覆盖子串类似,代码稍加改动即可
# https://leetcode-cn.com/problems/shortest-supersequence-lcci/