zoukankan      html  css  js  c++  java
  • 边工作边刷题:70天一遍leetcode: day 36

    Substring with Concatenation of All Words

    要点:用map对words计数,founds表示已经匹配的,patterns表示总共的。从左边words长度内的每一个点作为开始点,用sliding window来找到符合条件的串(记录start,根据当前的匹配情况移动start)。用总共匹配的word数目就可以判断是否找到匹配,而不需要比较每一个word的occurance。
    错误点:

    • 当找到一个匹配后,不需要移动start来重置。因为这时候founds里面全等于patterns,下一个word将会根据情况重置start
    • inner while loop:在检查当前word的时候,inner loop的条件是founds[cw]patterns[cw]。注意的条件,因为当前word还没有加入,需要去掉至少一个cw(同时还有所有左边从start开始的其他words)。另外不可能founds里的个数>patterns。当然最终因为founds[cw]<patterns[cw],需要在loop外面+1
    class Solution(object):
        def findSubstring(self, s, words):
            """
            :type s: str
            :type words: List[str]
            :rtype: List[int]
            """
            patterns = {}
            for w in words:
                if w not in patterns:
                    patterns[w]=0
                patterns[w]+=1
            
            wc = len(words)
            nw = len(words[0])
            res = []
            for i in range(nw):
                founds = {}
                count = 0
                start = i
                for j in range(i, len(s), nw):
                    cw = s[j:j+nw]
                    if cw in patterns:
                        count+=1
                        if cw not in founds:
                            founds[cw]=0
                            
                        if patterns[cw]>founds[cw]:
                            founds[cw]+=1
                        else:
                            while founds[cw]==patterns[cw]:
                                pw = s[start:start+nw]
                                start+=nw
                                founds[pw]-=1
                                count-=1
                            founds[cw]+=1
                        if count==wc:
                            res.append(start)
                            
                    else:
                        founds = {}
                        count = 0
                        start = j+nw
            return res
                
    
  • 相关阅读:
    程序员如何开始新的工作(转)
    Dom4j和Xpath(转)
    单例模式(Singleton)Holder
    请慎用java的File#renameTo(File)方法(转)
    How to append files to a .tar archive using Apache Commons Compress?(转)
    FindWindow使用方法
    sqlplus登录、连接命令
    hdu1217Arbitrage--解题报告
    String.Split()函数
    iOS_10_tableView的简单使用_红楼十二钗
  • 原文地址:https://www.cnblogs.com/absolute/p/5678238.html
Copyright © 2011-2022 走看看