题目描述(困难难度)
解题思路
python 代码
class Solution:
def findSubstring(self, s: str, words: List[str]) -> List[int]:
res = []
wordNum = len(words)
if wordNum == 0:
return res
wordLen = len(words[0])
# HashMap1 存所有单词
allWords = {}
for i in words:
value = allWords.get(i,0)
allWords[i] = value + 1
# 遍历所有子串
for i in range(len(s)-wordNum*wordLen+1):
# HashMap2 存当前扫描的字符串含有的单词
hashWords = {}
num = 0
# 判断该单词在HashMap1 中
while num < wordNum:
# s[0 + 0*3 : 0 + (0+1)*3]
# s[0 + 1*3 : 0 + (1+1)*3]
# s[0 + 2*3 : 0 + (2+1)*3]
word = s[i + num*wordLen : i + (num+1)*wordLen]
# 判断当前单词的value 和 HashMap1中该单词的value
if allWords.__contains__(word):
value = hashWords.get(word, 0)
hashWords[word] = value + 1
if hashWords.get(word) > allWords.get(word):
break
else:
break
num += 1
# 判断是不是所有的单词都符合条件
if num == wordNum:
res.append(i)
return res
s = Solution()
res = s.findSubstring("barfoothefoobarman",["foo","bar"])
print('.....',res)