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