博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
边工作边刷题:70天一遍leetcode: day 36
阅读量:4359 次
发布时间:2019-06-07

本文共 1812 字,大约阅读时间需要 6 分钟。

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

转载于:https://www.cnblogs.com/absolute/p/5678238.html

你可能感兴趣的文章
基于visual Studio2013解决面试题之1004最长等差数列
查看>>
联系方式
查看>>
基于visual Studio2013解决C语言竞赛题之0707月份输出
查看>>
【leetcode】Triangle
查看>>
PostgreSQL9.1 with PostGIS 2.1.4 for mapping coordinates on linux/ubuntu 已经打包成deb 可下载...
查看>>
[LeetCode] Max Consecutive Ones
查看>>
redis缓存本地安装教程
查看>>
ALTER AVAILABILITY GROUP (Transact-SQL)
查看>>
探究X Window System运行原理与启动过程
查看>>
Arch 安装 gnome桌面
查看>>
SpringCloud学习笔记(9)----Spring Cloud Netflix之声明式 REST客户端 -Feign的使用
查看>>
Python的平凡之路(17)
查看>>
Git for Windows之使用SSH协议开通公钥免密登陆功能
查看>>
Identity Server4学习系列一
查看>>
计算机硬件-基础
查看>>
完成登录功能,用session记住用户名
查看>>
C++ code:剩余串排列
查看>>
网页播放器插件
查看>>
Python第三方库jieba(中文分词)入门与进阶(官方文档)
查看>>
【转】eclipse for java ee的tomcat配置(常见问题解决)
查看>>