原题说明
Given a text
string and words
(a list of strings), return all index pairs [i, j]
so that the substring text[i]…text[j]
is in the list of words
.
Example 1:
Input: text = “thestoryofleetcodeandme”, words = [“story”,”fleet”,”leetcode”]
Output: [[3,7],[9,13],[10,17]]
Example 2:
Input: text = “ababa”, words = [“aba”,”ab”]
Output: [[0,1],[0,2],[2,3],[2,4]]
Explanation:
Notice that matches can overlap, see “aba” is found in [0,2] and [2,4].
Note:
- All strings contains only lowercase English letters.
- It’s guaranteed that all strings in
words
are different. 1 <= text.length <= 100
1 <= words.length <= 20
1 <= words[i].length <= 50
- Return the pairs
[i,j]
in sorted order (i.e. sort them by their first coordinate in case of ties sort them by their second coordinate).
解题思路
这道题可以直接用string find函数来做,但是需要分析一下时间复杂度。取决于具体的函数实现,比如CPP的find函数
没有用KMP实现,所以最坏的情况复杂度是O(M * N)
,这样带入本题,时间复杂度是O(M * sum(len(word)))
. 其中M
是text
的长度,sum(len(word))
是words
中word
的长度之和。
如果用字典树Trie来实现,则当M < sum(len(word))
时,时间复杂度可以优化。
首先建立基于words
的字典树trie,然后在text
中以每一个位置i
为起点向后遍历,并判断往后每一个位置j
是否在字典树中,若在则加入要返回的结果rets
中。
示例代码 (cpp)
1 | struct Trie { |
示例代码 (java)
1 | class Solution { |
示例代码 (python)
1 | class Solution: |
复杂度分析
时间复杂度: O(M^2 + sum(len(word)))
, M
为text
的长度
空间复杂度: O(26^max(len(words)))
视频讲解
我们在Youtube上更新了视频讲解,欢迎关注!