【发布时间】:2020-06-27 02:02:16
【问题描述】:
我正在解决以下问题:
给定一个字符串和一个单词列表,找到给定字符串中子字符串的所有起始索引,这些子字符串是所有给定单词的串联一次,没有任何单词重叠。假设所有单词的长度相同。例如:
输入:String = "catfoxcat", Words = ["cat", "fox"]
输出:[0, 3]
解释:包含两个单词的两个子字符串是“catfox”和“foxcat”。
我的解决办法是:
def find_word_concatenation(str, words):
result_indices = []
period = len(words[0])
startIndex = 0
wordCount = {}
matched = 0
for w in words:
if w not in wordCount:
wordCount[w] = 1
else:
wordCount[w] += 1
for endIndex in range(0, len(str) - period + 1, period):
rightWord = str[endIndex: endIndex + period]
if rightWord in wordCount:
wordCount[rightWord] -= 1
if wordCount[rightWord] == 0:
matched += 1
while matched == len(wordCount):
if endIndex + period - startIndex == len(words)*period:
result_indices.append(startIndex)
leftWord = str[startIndex: startIndex + period]
if leftWord in wordCount:
wordCount[leftWord] += 1
if wordCount[leftWord] > 0:
matched -= 1
startIndex += period
return result_indices
谁能帮我算出它的时间复杂度?
【问题讨论】:
-
你知道是否永远只有两个字吗?
-
不,可以有任意数量的单词,但所有单词的长度都相同。
-
单词的长度真的不是什么大问题。但这里还有一个问题要弄清楚你到底需要什么才能得到答案:假设你的单词表中有三个单词。你会期待(1,2),(2,1),(1,3),(3,1),(2,3),(3,2)吗?或者,加上 (1,2,3), (3,2,1), (2,3,1), (1,3,2), (3,1,2), (2,1,3 ) ?
标签: python substring time-complexity sliding-window