• 边工作边刷题:70天一遍leetcode: day 22


    Minimum Window Substring

    要点:同一思路的还有Substring with Concatenation of All Words, Longest Substring with At Most K Distinct Characters。基本要素是found map来记录当前sliding window中已经有的个数,用pattern map来记录满足pattern需要的个数。另外一个count变量就能知道是否当前sliding window和pattern匹配。
    Substring with Concatenation of All Words这题sliding window是固定的,所以found中某元素只要个数超过了就要移动左边界来重新match。而本题超过了found个数也+1,但count保持不变。这样,每次重新移动调整左边界的内循环里也是去除无关或者超过的元素,从而保持sliding window中永远是match的,而是否sliding window中有超过pattern的字符是无所谓的。
    错误点:

    • pattern和found别搞混,这里很容易typo
    • 因为只有match的情况才更新minLen,所以对不match要特殊处理
    class Solution(object):
        def minWindow(self, s, t):
            """
            :type s: str
            :type t: str
            :rtype: str
            """
            ns = len(s)
            nt = len(t)
            pattern = {}
            found = {}
            for tc in t:
                if tc not in pattern:
                    pattern[tc]=0
                pattern[tc]+=1
            
            count = 0
            start = 0
            minLen = sys.maxint
            minStart = -1
            for i in range(len(s)):
                if s[i] not in pattern:
                    continue
                
                if s[i] not in found:
                    found[s[i]]=0
                found[s[i]]+=1
                if found[s[i]]<=pattern[s[i]]:
                    count+=1
                
                #print found,pattern
                if count==nt:
                    while start<ns:
                        if s[start] not in pattern:
                            start+=1
                        elif pattern[s[start]]<found[s[start]]:
                            found[s[start]]-=1
                            start+=1
                        else:
                            break
    
                    if i-start+1<minLen:
                        minLen = i-start+1
                        minStart = start
            if minStart==-1: return ""
            #print minStart
            return s[minStart:minStart+minLen]
                
                
    
  • 相关阅读:
    CET成绩批量查询
    c++常用库简介
    1985年以来微软、苹果、Google赚了多少钱?
    试试PT建站脚本
    补门~
    网站提交大全
    uniapp接入人身核验小程序
    【odoo】【知识杂谈】关于菜单及记录规则中“非”计算的改造
    【odoo】【知识杂谈】关于odoo二开模块规范的一点思考
    mysql拒绝访问
  • 原文地址:https://www.cnblogs.com/absolute/p/5677975.html
Copyright © 2020-2023  润新知