Note, word = “” + word is a valid segmentation as long as word is in wordDict.
Dynamic programming
Subproblem
Let denote if the prefix
can be broken into words. Then:
Note, we assume an empty string can be segmented.
Order
Edges go from smaller ‘s to a bigger
. Processing in the order of increasing
gives us a topological order.
There are subproblems. The
-th subproblem depends on
earlier subproblems each of which requires a
str-slicing. So, total time: , space:
.
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
n = len(s)
word_set = set(wordDict)
dp = [True] + [False]*n
for i in range(1, n+1):
for j in range(i, 0, -1):
if dp[j-1] and s[j-1:i] in word_set:
dp[i] = True
break
return dp[n]
Trie
If wordBreak() is called often with the same wordDict but for different s‘s, turning wordDict into a trie and reusing that trie might help.
Leave a comment