problem 30
30. Substring with Concatenation of All Words
Hard
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.
Example 1:
1 | |
Example 2:
1 | |
这个题关键的一点在于所有的单词长度一样,如果不一样,复杂度感觉爆炸
既然长度一样,就可以采用滑窗的思路来解题
假设单词的长度为N,一共n的单词,则一个窗口长度为n*N
然后及时如何滑窗的问题了
假设4个单词,长度为4,初始窗口如下
|—-|—-|—-|—-|
第一种滑窗的思路
.|—-|—-|—-|—-|
..|—-|—-|—-|—-|
这种滑窗会导致重复计算
第二种思路
先每次滑动N,这样可以继承前面计算的结果
1 | |
第二种滑窗
1 | |
1664 ms ->304 ms(144 ms)