【问题标题】:Time complexity of a sliding window question滑动窗口问题的时间复杂度
【发布时间】: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


【解决方案1】:

我们应该首先区分您的代码的时间复杂度与您可能实际寻找的时间复杂度。

在您的情况下,您有一组嵌套循环(for 和 while)。因此,最坏的情况,即 Big O 所基于的,您将执行每个 while 循环 n 次。但是你也有那个外部循环,它也会被执行 n 次。

O(n) * O(n) = O(n) 2

这不是很好。现在,虽然这个例子并没有那么糟糕,但想象一下,如果您在所有国会图书馆甚至莎士比亚文集中寻找“什么是人的作品”。

从好的方面来说,您可以重构您的代码并将其降低很多。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 2013-01-17
    • 1970-01-01
    相关资源
    最近更新 更多