題目描述
給定一個字符串 s 和一些長度相同的單詞 words。找出 s 中恰好可以由 words 中所有單詞串聯(lián)形成的子串的起始位置。
注意子串要與 words 中的單詞完全匹配,中間不能有其他字符,但不需要考慮 words 中單詞串聯(lián)的順序。
示例 1:
輸入:
s = "barfoothefoobarman",
words = ["foo","bar"]
輸出:[0,9]
解釋:
從索引 0 和 9 開始的子串分別是 "barfoor" 和 "foobar" 。
輸出的順序不重要, [9,0] 也是有效答案。
示例 2:
輸入:
s = "wordgoodgoodgoodbestword",
words = ["word","good","best","word"]
輸出:[]
思路:
思路很清新,遍歷每一個可能的位置,匹配是否能夠匹配
from collections import Counter
class Solution:
def findSubstring(self, s, words):
if not s or not words:
return []
res = []
one_lens = len(words[0])
lens = len(words) * one_lens
words = Counter(words)
for i in range(len(s) - lens + 1):
temp = s[i:i+lens]
child_words = []
for j in range(0, lens, one_lens):
child_words.append(temp[j:j + one_lens])
if Counter(child_words) == words:
res.append(i)
return res

Ac30