您的位置:首页 > 编程语言 > Python开发

[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]

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: