leetcode_1065 字符串的索引对

168 阅读1分钟

要求

给出 字符串 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 中的字符串无重复。
  • 1 <= text.length <= 100
  • 1 <= words.length <= 20
  • 1 <= words[i].length <= 50
  • 按序返回索引对 [i,j](即,按照索引对的第一个索引进行排序,当第一个索引对相同时按照第二个索引对排序)

核心代码

class Solution:
    def indexPairs(self, text: str, words: List[str]) -> 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

image.png

解题思路:我们先统计字符的个数,将相同字符个数的word放到同一个列表中,构建字典,然后使用两层循环进行遍历,两次循环就是为了做差,然后我们可以在数字字典进行word的扫描,单词不同,一旦扫描到,break即可。