[LeetCode]题解(python):030-Substring with Concatenation of All Words
2015-10-21 20:27
495 查看
[b]题目来源:[/b]
https://leetcode.com/problems/substring-with-concatenation-of-all-words/
[b]题意分析:[/b]
输入一个字符串s和一连串的长度相同的字符串数组words,找出仅由所有的words组成的s的子字符串起始位置。
[b]题目思路:[/b]
由于给定的words的长度是相同的,题目难度就降低了很多。题目难度就在于判断一个字符串是否仅由words构成。这里,我们可以构造一个字典,key对应的是words出现的次数。将字符串截成n个words长度的字符串,如果这些字符串出现在字典里面,字典对应的次数-1.如果所有字典为0则满足。
[b]代码(python):[/b]
View Code
转载请注明出处:http://www.cnblogs.com/chruny/p/4898993.html
https://leetcode.com/problems/substring-with-concatenation-of-all-words/
[b]题意分析:[/b]
输入一个字符串s和一连串的长度相同的字符串数组words,找出仅由所有的words组成的s的子字符串起始位置。
[b]题目思路:[/b]
由于给定的words的长度是相同的,题目难度就降低了很多。题目难度就在于判断一个字符串是否仅由words构成。这里,我们可以构造一个字典,key对应的是words出现的次数。将字符串截成n个words长度的字符串,如果这些字符串出现在字典里面,字典对应的次数-1.如果所有字典为0则满足。
[b]代码(python):[/b]
class Solution(object): def match(self,s,dict,size): i = 0 while i <= len(s)- size: tmp = s[i:i + size] if tmp in dict and dict[tmp] != 0: dict[tmp] -= 1 else: return False i += size return True def findSubstring(self, s, words): """ :type s: str :type words: List[str] :rtype: List[int] """ sizew = len(words) if sizew == 0: return [] d = {} ans = [] for i in words: if i in d: d[i] += 1 else: d[i] = 1 j = 0 ss = len(s); sw = len(words[0]) while j <= ss - sizew * sw: tmpd = d.copy() if self.match(s[j:j + sizew * sw],tmpd,sw): ans.append(j) j += 1 return ans
View Code
转载请注明出处:http://www.cnblogs.com/chruny/p/4898993.html
相关文章推荐
- Python之继承
- python中super出现的TypeError: must be type, not classobj 原因及解决
- Python包和模块
- 「Python」利用OpenGL作渲染以及离屏渲染
- urllib2库.官方文档翻译
- Python时间,日期,时间戳之间转换
- Python GUI - Tkinter tkMessageBox
- Sublime Text 3 装了Anaconda 写Python代码出现框框的解决办法
- Python里的*args和**kwargs是什么?
- Python学习笔记3
- python struct.pack中的对齐字节问题
- 选择排序算法Java与Python实现
- 【Python】爬虫小结
- python,用django开始第一个网页
- python---格式化字符
- python 全入门手册
- 不要嫌我啰嗦~继续话痨python
- python gui 练习
- 【TypeError: only length-1 arrays can be converted to Python scalars】
- python list 自定义排序