码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode]题解(python):030-Substring with Concatenation of All Words

时间:2015-10-21 20:59:51      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

题目来源:

  https://leetcode.com/problems/substring-with-concatenation-of-all-words/


 

题意分析:

  输入一个字符串s和一连串的长度相同的字符串数组words,找出仅由所有的words组成的s的子字符串起始位置。


 

题目思路:

  由于给定的words的长度是相同的,题目难度就降低了很多。题目难度就在于判断一个字符串是否仅由words构成。这里,我们可以构造一个字典,key对应的是words出现的次数。将字符串截成n个words长度的字符串,如果这些字符串出现在字典里面,字典对应的次数-1.如果所有字典为0则满足。


 

代码(python):

技术分享
 1 class Solution(object):
 2     def match(self,s,dict,size):
 3         i = 0
 4         while i <= len(s)- size:
 5             tmp = s[i:i + size]
 6             if tmp in dict and dict[tmp] != 0:
 7                 dict[tmp] -= 1
 8             else:
 9                 return False
10             i += size
11         return True
12     def findSubstring(self, s, words):
13         """
14         :type s: str
15         :type words: List[str]
16         :rtype: List[int]
17         """
18         sizew = len(words)
19         if sizew == 0:
20             return []
21         d = {}
22         ans = []
23         for i in words:
24             if i in d:
25                 d[i] += 1
26             else:
27                 d[i] = 1
28         j = 0
29         ss = len(s); sw = len(words[0])
30         while j <= ss - sizew * sw:
31             tmpd = d.copy()
32             if self.match(s[j:j + sizew * sw],tmpd,sw):
33                 ans.append(j)
34             j += 1
35         return ans
View Code

 


 

转载请注明出处:http://www.cnblogs.com/chruny/p/4898993.html

[LeetCode]题解(python):030-Substring with Concatenation of All Words

标签:

原文地址:http://www.cnblogs.com/chruny/p/4898993.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!