python写算法题:leetcode: 30. Substring with Concatenation of All Words
来源:互联网 发布:o2o创业项目 php 编辑:程序博客网 时间:2024/06/07 19:22
https://leetcode.com/problems/substring-with-concatenation-of-all-words/#/description
class Solution(object): def matchstr(self, p0, p1, wordsind, wlen, posmap): wv={} for w in wordsind.keys(): wv[w]=0 for i in xrange(p0, p1, wlen): if i in posmap: wv[posmap[i]]+=1 return wv def findSubstring(self, s, words): """ :type s: str :type words: List[str] :rtype: List[int] """ if len(words)==0: return [] wlen = len(words[0]) wordsind = {} wcnt={} posmap={} for w in words: if w in wordsind: wcnt[w]+=1 continue else: matchlst=[] wcnt[w]=1 i=0 while i>=0: i = s.find(w, i) if i>=0: posmap[i]=w matchlst.append(i) i+=1 wordsind[w]=matchlst res=[] endpos=len(words)*wlen-wlen for p0 in xrange(len(words[0])): wv = self.matchstr(p0, p0+len(words)*wlen, wordsind, wlen, posmap) if wv == wcnt: res.append(p0) for p in xrange(p0+wlen, len(s)-endpos, wlen): if p-wlen in posmap: wv[posmap[p-wlen]]-=1 if p+endpos in posmap: wv[posmap[p+endpos]]+=1 if wv == wcnt: res.append(p) return res
思路:充分利用匹配串长度相同规则,开头匹配偏移取值是单个匹配窜的长度范围,然后跳跃式的检查是否满足要求,最终运算复杂度为 O(n+m)
阅读全文
0 0
- python写算法题:leetcode: 30. Substring with Concatenation of All Words
- [Leetcode]30. Substring with Concatenation of All Words @python
- 【Leetcode】【python】Substring with Concatenation of All Words
- LeetCode: Substring with Concatenation of All Words
- LeetCode : Substring with Concatenation of All Words
- [Leetcode] Substring with Concatenation of All Words
- [LeetCode]Substring with Concatenation of All Words
- LeetCode-Substring with Concatenation of All Words
- [LeetCode] Substring with Concatenation of All Words
- LeetCode:Substring with Concatenation of All Words
- Leetcode: Substring with Concatenation of All Words
- [LeetCode] Substring with Concatenation of All Words
- leetcode Substring with Concatenation of All Words
- leetcode Substring with Concatenation of All Words
- LeetCode Substring with Concatenation of All Words
- LeetCode | Substring with Concatenation of All Words
- LeetCode - Substring with Concatenation of All Words
- Substring with Concatenation of All Words -- LeetCode
- 读书笔记-真实的诸葛亮-1
- css属性
- [LeetCode] 35. Search Insert Position
- 前自增的学习和自我探讨
- 授权MySQL数据库远程连接的权限
- python写算法题:leetcode: 30. Substring with Concatenation of All Words
- 图论——calling circls
- c语言基础——运算符表达式
- 【转】SPSS与EXCEL的比较
- 在windows上面建立端口传文件
- ReactNative获取ListView当前界面展示的row的个数
- Android 如何对apk文件进行反编译以及重新打包签名 标签: apktoolandroid反编译jebSmali2Java 2016-05-10 16:00 3897人阅读 评论(0) 收藏
- jzoj. 3873. 【NOIP2014八校联考第4场第2试10.20】乐曲创作(music)
- 堆与堆排序