【问题标题】:Time Complexity Analysis for Word Break分词的时间复杂度分析
【发布时间】:2020-04-12 15:53:52
【问题描述】:

以下代码的时间复杂度分析和空间复杂度分析是什么:

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        if not s or not dict:
            False

        N=len(s)
        ans=[False for i in range (N+1)]
        ans[0]=True


        for index in range(N):
            if ans[index]:
                for word in wordDict:
                    L=len(word)
                    if index+L <= N and s[index:index+L]==word:
                        ans[index+L]=True

        return ans[-1]

给定一个非空字符串s 和一个包含非空单词列表的字典wordDict,确定s 是否可以分割成一个或多个字典单词的空格分隔序列。

【问题讨论】:

  • O(N * |wordDict|)

标签: python time-complexity big-o


【解决方案1】:

此解决方案的时间复杂度为 O(n*m*k) - 其中:

  • n 是字符串s 的长度。
  • mwordDict 中的字数。
  • kwordDict 中单词的平均长度。

说明,您重复n 次,每次检查wordDict 中的每个单词(m 总数),并且对于每个这样的重复,您阅读整个单词(长度为k)。

空间复杂度为O(n) - 您的辅助数组独立于wordDict 中的单词数或其长度,并且没有额外的空间分配1取决于字典。


(1) 好吧,我不确定python是如何实现s[index:index+L]的,但无论哪种方式,这都不会被n倍增,并且一次不会分配超过一次,如果L &gt; n也不会分配- 所以它不会影响空间复杂度。

【讨论】:

    猜你喜欢
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 2015-01-26
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多