dp[i] is True if s[:i] can be segmented into dictionary words. For each position i, we check all possible previous positions j where dp[j] is True and s[j:i] is in the dictionary.
- Create a boolean
dparray of sizen + 1, withdp[0] = True. - For each position
ifrom 1 to n:- For each
jfrom 0 to i: ifdp[j]is True ands[j:i]is inwordDict, setdp[i] = True.
- For each
- Return
dp[n].
- Time Complexity: O(N^2 * M) where M is the max word length.
- Space Complexity: O(N).
def word_break(s, word_dict):
word_set = set(word_dict)
n = len(s)
dp = [False] * (n + 1)
dp[0] = True
for i in range(1, n + 1):
for j in range(i):
if dp[j] and s[j:i] in word_set:
dp[i] = True
break
return dp[n]