给出 字符串 text
和 字符串列表 words
, 返回所有的索引对 [i, j]
使得在索引对范围内的子字符串 text[i]...text[j]
(包括 i
和 j
)属于字符串列表 words
。
示例 1:
输入: text = "thestoryofleetcodeandme", words = ["story","fleet","leetcode"]
输出: [[3,7],[9,13],[10,17]]
示例 2:
输入: text = "ababa", words = ["aba","ab"]
输出: [[0,1],[0,2],[2,3],[2,4]]
解释:
注意,返回的配对可以有交叉,比如,"aba" 既在 [0,2] 中也在 [2,4] 中
提示:
思路:
先建立字典,把words里的元素按长度分类,key是words里每个word的长度,val是长度为key的所有word,
然后对于text的每个子字符串substring = text[i:j],用N ^ 2的双重循环找出来,
先判断字典里有没有长度为len(substring) = j - i的这个key, 如果没有说明不用考虑了,
如果有这个key,那么把这个key对应的val找出来,逐个判断能不能匹配。
- 所有字符串都只包含小写字母。
- 保证
words
中的字符串无重复。 1 <= text.length <= 100
1 <= words.length <= 20
1 <= words[i].length <= 50
- 按序返回索引对
[i,j]
(即,按照索引对的第一个索引进行排序,当第一个索引对相同时按照第二个索引对排序)。
class Solution(object):
def indexPairs(self, text, words):
"""
:type text: str
:type words: List[str]
:rtype: List[List[int]]
"""
res = []
record = {}
for word in words:
if record.get(len(word), -1) == -1:
record[len(word)] = [word]
else:
record[len(word)].append(word)
l = len(text)
for i in range(l):
for j in range(i + 1, l + 1):
if record.get(j - i, -1) == -1:
continue
tmp = text[i:j]
for word in record[j - i]:
if word == tmp:
res.append([i, j - 1])
break
return res