1. 题目
2. 解析
使用滑动窗口,注意长度相同的wodrs,采用单词统计计数
3. 核心代码
from typing import List
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
n = len(s)
m = len(words)
w_l = len(words[0])
window_size = m * w_l
cnt = {word: 0 for word in words}
word_cnt = cnt.copy()
for word in words:
word_cnt[word] += 1
start = 0
ans = []
while start < n - window_size + 1:
tmp = cnt.copy()
for i in range(start, start + window_size, w_l):
part = s[i:i + w_l]
if part not in word_cnt:
break
tmp[part] += 1
if tmp[part] > word_cnt[part]:
break
else:
ans.append(start)
start += 1
return ans
if __name__ == '__main__':
s = Solution()
print(s.findSubstring('barfoothefoobarman', ["foo", "bar"]))