示例 1:
输入:
s = “barfoothefoobarman”,
words = [“foo”,“bar”]
输出:[0,9]
解释:
从索引 0 和 9 开始的子串分别是 “barfoor” 和 “foobar” 。
输出的顺序不重要, [9,0] 也是有效答案。
示例 2:
输入:
s = “wordgoodgoodgoodbestword”,
words = [“word”,“good”,“best”,“word”]
输出:[]
暴力匹配用了1700ms多:
class Solution:
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
if not words:
return []
len_word, length = len(words[0]), len(words)
len_words, word_dict, res = len_word * length, {
}, []
for word in words:
word_dict[word] = word_dict.get(word, 0) + 1
for i in range(len(s)-len_words+1):
dict_s = {
} # 求每个点开始的words_dict
for j in range(length):
word = s[i+j*len_word:i+(j+1)*len_word]
dict_s[word] = dict_s.get(word, 0) + 1
if dict_s == word_dict:
res.append