【问题标题】:Time Complexity of this Word Break DFS + Memorization solution此 Word Break DFS + 记忆解决方案的时间复杂度
【发布时间】:2021-01-27 07:02:25
【问题描述】:

在处理 wordBreak 问题时,我发现这个解决方案非常简洁。但不确定时间复杂度。有人可以帮忙吗?

我的理解是最坏的情况,O(n*k),n是wordDict的大小,k是String的长度。

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        return wordBreak(s, wordDict, new HashMap<String, Boolean>());
    }
    
    private boolean wordBreak(String s, List<String> wordDict, Map<String, Boolean> memo) {
        if (s == null) return false;
        
        if (s.isEmpty()) return true;
        
        if (memo.containsKey(s)) return memo.get(s);
        
        for (String dict : wordDict) { //number of words O(n)
                            //startsWith is bounded by the length of dict word, avg is O(m), can be ignored
                            //substring is bounded by the length of dict word, avg is O(k), k is the length of s
                            //wordBreak will be executed k/m times, k is the length of s, worse case k times... when a single letter is in the dict
            if (s.startsWith(dict) && wordBreak(s.substring(dict.length()), wordDict, memo)) {
                memo.put(s, true);
                return true;
            } 
        }
        memo.put(s, false);
        return false;
    }
}

【问题讨论】:

    标签: algorithm word-break


    【解决方案1】:

    由于以下几个原因,它比 O(nk) 更糟糕:

    1. 你忽略了“m”,但m 是 Omega(log k)。 (因为 k
    2. s.substring 可能是 O(n)。您的代码看起来像 Java,在 Java 中是 O(n)。
    3. 即使s.substring 是线性的,您的 Map 也需要对字符串进行哈希处理,因此您的映射操作是 O(n)(请注意——n 是字符串的大小而不是像通常那样的哈希表)。

    这可能意味着您的复杂度为 O(n^2k*logk)。

    您可以轻松修复 3 -- 您可以使用 s.length 而不是 s 作为哈希表的键。

    问题 2 很容易解决,但有点烦人——您可以使用一个变量来索引字符串,而不是对字符串进行切片。您可能必须自己重写startsWith 才能使用此索引(或使用特里——见下文)。如果您的编程语言有 O(1) 切片操作(例如,C++ 中的 string_view),那么您可以使用它。

    问题 1 只是理论上的问题,因为对于真实的单词列表,与字典的长度或输入字符串的潜在长度相比,m 确实很小。

    请注意,对字典使用 trie 而不是单词列表可能会大大缩短时间,实际示例是线性的,不包括字典构造(尽管恶意选择字典和输入字符串的最坏情况示例会为 O(nk))。

    【讨论】:

      猜你喜欢
      • 2020-11-13
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 2014-02-11
      • 1970-01-01
      • 1970-01-01
      • 2023-02-21
      • 1970-01-01
      相关资源
      最近更新 更多