python - 滑动窗口问题的时间复杂度
问题描述
我正在解决以下问题:
给定一个字符串和一个单词列表,找到给定字符串中的所有子字符串的起始索引,这些子字符串是所有给定单词的串联一次,没有任何单词重叠。假设所有单词的长度相同。例如:
输入: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
谁能帮我弄清楚它的时间复杂度吗?
解决方案
推荐阅读
- regex - 正则表达式交换日期
- linux - SOCK_DGRAM 和 SOCK_STREAM 在上下文 AF_UNIX 套接字中的用途是什么?
- go - 在项目目录中找不到包
- animation - 谷歌地球 kml 动画更新多个更改
- javascript - Ionic 3 多个小尺寸模态与一个带有 if 条件的大模态
- android - Playstore 上的“立即尝试”选项不可用,打开链接显示未找到
- android - 此代码每次在内部存储中创建文件夹,我需要在我的 SDCARD 中创建文件夹
- algorithm - 如何将强连通分量减少到一个顶点?
- c# - 以下连接字符串有什么问题?
- awk - 使用 awk 从 url 中提取文件