问题描述:
给定一个字符串s
和一些长度相同的单词words
。在s
中找出可以恰好串联 words
中所有单词的子串的起始位置。
注意子串要与words
中的单词完全匹配,中间不能有其他字符,但不需要考虑words
中单词串联的顺序。
示例 1:
输入:
s = “barfoothefoobarman”,
words = [“foo”,“bar”]
输出: [0,9]
解释: 从索引 0 和 9 开始的子串分别是 “barfoor” 和 “foobar” 。
输出的顺序不重要, [9,0] 也是有效答案。
示例 2:
输入:
s = “wordgoodstudentgoodword”,
words = [“word”,“student”]
输出: []
问题分析:
这个题目看着很复杂,其实不难,可以用滑动窗口的方法解决,先把 words
中的所有单词进行放到一个字典中,然后扫描字符串s
,一个窗口一个窗口的统计分析,把符合的小窗口的起始位置保存结果变量里,即可。
Python3实现:
# @Time :2018/09/24
# @Author :LiuYinxing
class Solution:
def findSubstring(self, s, words):
if len(words) == 0: return []
wordsDict = {}
for word in words: # 统计每个单词出现的个数
if word not in wordsDict:
wordsDict[word] = 1
else:
wordsDict[word] += 1
n, m, k = len(s), len(words[0]), len(words) # n, m, k 分别表示,字符串的长度,单词的长度,单词的个数
res = []
for i in range(n - m * k + 1): # 选择一个区间或者窗口
j = 0
cur_dict = {}
while j < k:
word = s[i + m * j:i + m * j + m] # 区间内选择一个单词
if word not in wordsDict: # 出现不存在的单词,直接结束本此区间
break
if word not in cur_dict:
cur_dict[word] = 1
else:
cur_dict[word] += 1
if cur_dict[word] > wordsDict[word]: # 某个单词大于所需,则直接结束本此区间
break
j += 1 # 单词数加一
print(j)
if j == k: res.append(i) # 记录起始位置
return res
if __name__ == '__main__':
solu = Solution()
s, words = 'barfoothefoobarman', ['foo', 'bar']
print(solu.findSubstring(s, words))
声明: 总结学习,有问题可以批评指正,大神可以略过哦
题目链接:leetcode-cn.com/problems/substring-with-concatenation-of-all-words/description/