zoukankan      html  css  js  c++  java
  • 边工作边刷题: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]
                
                
    
  • 相关阅读:
    linux脚本练习之将数据导入oracle表
    linux脚本之一个程序调用另一个程序
    使用客户端Navicat连接数据库oracle19c
    centos7安装与卸载oracle19c
    Redis-cluster集群搭建(redis版本5.0.4)
    linux下redis的哨兵模式
    使用POI导入Excel文件
    MySQL8.0搭建MGR集群(MySQL-shell、MySQL-router)
    MySQL Shell用法
    CentOS 7下使用rpm包安装MySQL8.0
  • 原文地址:https://www.cnblogs.com/absolute/p/5677975.html
Copyright © 2011-2022 走看看