Table of Content
题目如下:
通过滑动窗口来取子字符串,并通过字典对象比较单词的出现次数可以求解这个问题。参考代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
class Solution: def findSubstring(self, s, words): """ :type s: str :type words: List[str] :rtype: List[int] """ # 初始化 strlen = 0 res = [] if strlen > len(s) or len(s) == 0 or len(words) == 0: return res dic_words = {} # 转换为字典,并计算出现次数 for w in words: if w in dic_words: dic_words[w] += 1 else: dic_words[w] = 1 # 子串长度 len_word = len(words[0]) len_words = len(words) strlen += len_word * len_words j = 0 # 子串滑动窗口 while j + strlen <= len(s): dic_substr = {} substr = s[j: j + strlen] k = 0 # 单词滑动窗口 while k + len_word <= len(substr): if substr[k: k + len_word] in dic_words: if substr[k: k + len_word] in dic_substr: dic_substr[substr[k: k + len_word]] += 1 else: dic_substr[substr[k: k + len_word]] = 1 k = k + len_word else: break if dic_words == dic_substr: res.append(j) j = j + 1 return res |
如果您有好的建议,欢迎来信与我交流

也欢迎关注微信公众号“苔原带”

