题目描述
解题思路
一开始考虑的就是暴力破解,每次切片切words中字母的个数,然后根据每个词语的长度进行进一步的切片,将切出来的单词放入列表,然后每次对比一次,如果存在,就从原来的列表中,删除一个元素,最后复制的words数组为空,结束,找到起始位置i,将其加入结果列表中。很遗憾,这种方法超时。然后,优化的方法是使用的哈希表计数的方法,具体的代码如下。
超时方法
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
templist=[]
result=[]
length=len(words)
if len(s)<length*len(words[0]):
return result
for i in range(len(s)):
if i+length*len(words[0])>len(s):
break
tempstr=s[i:i+length*len(words[0])]
list1=[tempstr[i:i+len(words[0])] for i in range(0, len(tempstr), len(words[0]))]
list2=[item for item in words]
for item in list1:
if item in words and item in list2:
list2.remove(item)
else:
break
if len(list2)==0:
result.append(i)
return result
正常方法
from collections import Counter
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
result = []
word_count = Counter(words)
word_len = len(words[0])
total_len = len(words) * word_len
for i in range(len(s) - total_len + 1):
substr_count = Counter()
j = 0
while j < len(words):
word = s[i + j * word_len : i + (j + 1) * word_len]
if word not in word_count:
break
substr_count[word] += 1
if substr_count[word] > word_count[word]:
break
j += 1
if j == len(words):
result.append(i)
return result