You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.
For example, given:
s:"barfoothefoobarman"
words:["foo", "bar"]
You should return the indices:
[0,9]
.
(order does not matter).
利用滑动窗口搜索的方式
计算每个word在words中出现的次数
设置窗口,l为窗口左端点,r为窗口右端点,左闭右开,window记录窗口中每个单词的数量wordmap
从0~len(word)-1开始枚举左端点的起点
- 扩展窗口,r不断的右移一个len(word)
- 如果当前最右边的单词不在words中,则清理窗口 l = r
- 如果在,window[word] += 1
window[word] < wordmap[word]
继续扩展window[word] == wordmap[word]
检查是不是一个解,即r-l == len(word)*len(words)
window[word] > wordmap[word]
进入步骤2
- 收缩窗口,l不断右移一个len(word),window[l] -= 1,检查
window[s[r-len:r]] == wordmap[s[r-len:r]]
- 扩展窗口,r不断的右移一个len(word)
1 | class Solution: |