SDE & MLE Prep

139. Word Break

Problem

Decide whether s can be split into a sequence of one or more words from wordDict (words may be reused).

Example: s = "applepenapple", wordDict = ["apple","pen"] → true; s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] → false

Constraints: length ≤ 300.

dp[i] = s[:i] can be segmented = exists j < i with dp[j] and s[j:i] in the dictionary. Limit j to the max word length.

Complexity: O(n · L) substring checks.

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        words = set(wordDict)
        L = max(map(len, words))
        dp = [True] + [False] * len(s)
        for i in range(1, len(s) + 1):
            for j in range(max(0, i - L), i):
                if dp[j] and s[j:i] in words:
                    dp[i] = True
                    break
        return dp[-1]