描述:给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。
class Solution:
def findSubstring(self, s: str, words):
if words and s:
longth = len(words[0]) # 单词长度
totallongth = len(words) * longth # 总共长度
else:
return []
if len(s) < totallongth:
return []
ans = [] # 存储索引的列表
for i in range(len(s) - totallongth + 1):
res = [] # 存放当前指针开始的totallongth长度的字符串
if s[i:i + longth] not in words: # 如果第一个单词不在words中,开始下一轮循环
continue
else:
for j in range(i, i + totallongth, longth):
res.append(s[j:j + longth]) # 以单词长度为分隔条件,把所有子串加入列表
for index, item in enumerate(res):
if res.count(item) != words.count(item): # 查看当前单词的个数是否与words中单词数目一致
break
if index == len(res) - 1: # 如果到了最后也没跳出循环,那就判断是不是最后一个单词
ans.append(i)
return ans
思路简单点来说就是根据words的单词总长度(个数*单个长度)
来滑动字符串,分割完成后检查每个单词个数是否与words中一致
速度的话也还可以了