Python 学习日记 (5) LeetCode 30

LeetCode 30

把所有word都放入一个dictionary,可以快速查找。然后有一个sliding window来不断的做检查。比较trick的地方是,如果我们从0的位置开始匹配,如果不能成功匹配,还得从1的地方开始,但是字符串是固定长度的,所以可以只需要从0到固定长度-1的位置开始匹配,后面的case已经处理过了。

from typing import List
import collections

class Solution:
    def findSubstring(self, s: str, words: List[str]) -> List[int]:        
        result = list()

        if len(words) == 0 or len(s) == 0:
            return result        

        wanted = len(words)
        lenWord = len(words[0])
        lenStr = len(s)

        if lenStr < lenWord * wanted:
            return result

        wordDict = collections.defaultdict(int)
        for word in words:            
            wordDict[word] += 1
        
        for i in range(lenWord):
            start, count = i, 0
            tempDict = collections.defaultdict(int)
            for j in range(start, lenStr-lenWord + 1, lenWord):
                curStr = s[j: j+lenWord]
                if curStr in wordDict:
                    tempDict[curStr] +=1
                    count+=1
                    while tempDict[curStr] > wordDict[curStr]:
                        tempDict[s[start:start+lenWord]] -=1
                        start+=lenWord
                        count -=1
                    
                    if count == wanted:
                        result.append(start)
                else:
                    tempDict = collections.defaultdict(int)
                    start = j+lenWord
                    count = 0

        return result

今天用到了dictionary,并且用了collections里面的一些函数。https://docs.python.org/3/library/collections.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值