You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Time Complexity: O(k * n * (n + m)), or O(k * n^2) when m <= n
40
43
- n = len(s)
41
-
- k = number of words in wordDict
42
-
- m = average word length in wordDict
44
+
- k = len(wordDict)
45
+
- m = the maximum word length
43
46
44
-
For every index in s, we consider each word in wordDict and, for each, match up to m characters.
47
+
Each of the n + 1 prefix boundaries checks every word. The expression
48
+
s[index - W:] creates a suffix of up to O(n) characters, and startswith
49
+
may compare up to m characters.
45
50
46
51
Space Complexity: O(n)
47
-
- n = len(s), required for the dp array.
48
-
49
-
- Uses bottom-up dynamic programming.
50
-
- The dp array indicates whether a prefix of s up to index can be segmented into words from wordDict.
51
-
- Base case: dp[0] = 1, since the empty string can always be segmented.
52
-
- For each index, iterate through all words, and for each, check if s[index - W : index] equals the word, assuming index >= W and dp[index - W] is True.
53
-
- If a match is found, update dp[index] to reflect that segmentation.
54
-
- Finally, return True if dp[-1] is set, indicating the entire string can be segmented; otherwise, return False.
52
+
The dp array stores one value for every prefix boundary.
53
+
54
+
dp[index] indicates whether s[:index] can be segmented. dp[0] is true because
55
+
the empty prefix needs no words. A word of length W can end at index when the
56
+
preceding prefix, dp[index - W], is valid and the suffix beginning there starts
57
+
with that word. The final entry represents the entire string.
0 commit comments