LeetCode-Python-1065. 字符串的索引对

658 篇文章 23 订阅

给出 字符串 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找出来,逐个判断能不能匹配。

  1. 所有字符串都只包含小写字母。
  2. 保证 words 中的字符串无重复。
  3. 1 <= text.length <= 100
  4. 1 <= words.length <= 20
  5. 1 <= words[i].length <= 50
  6. 按序返回索引对 [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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值