Word Break Problem
Description
LeetCode Problem 139.
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = "leetcode", wordDict = ["leet","code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:
Input: s = "applepenapple", wordDict = ["apple","pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
Output: false
Constraints:
- 1 <= s.length <= 300
- 1 <= wordDict.length <= 1000
- 1 <= wordDict[i].length <= 20
- s and wordDict[i] consist of only lowercase English letters.
- All the strings of wordDict are unique.
Solution
Approach: Dynamic Programming over Prefixes
Trying every way to cut the string is exponential: with s = "aaa…ab" and wordDict = ["a", "aa", "aaa", …], a plain recursion explores a huge number of splits before failing. But the only thing that matters about a split point is whether the part before it can be broken into words, and there are only n + 1 such prefixes.
Let canBreak[i] be true when the prefix s[0..i) (the first i characters) splits into dictionary words.
canBreak[0] = true: the empty prefix needs no words.- For each
endfrom 1 ton,canBreak[end]is true if somestart < endhascanBreak[start]true ands[start..end)in the dictionary. That word is the last word of the prefix. - The answer is
canBreak[n].
Put the words in a hash set so each lookup is fast. Also, no dictionary word is longer than longest (at most 20), so start only needs to go back longest characters from end. Checking all start values is still correct, just slower for long strings.
For s = "leetcode": canBreak[4] is true because "leet" is a word, and canBreak[8] is true because canBreak[4] is true and "code" is a word.
Complexity: O(n · L2) time, where n is the length of s and L is the length of the longest word: each of the n · L candidate words takes O(L) to cut out and hash. O(n + total length of wordDict) space for the table and the set.
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
words = set(wordDict)
longest = max(len(word) for word in wordDict)
n = len(s)
# can_break[i] is True when the prefix s[:i] splits into dictionary words.
can_break = [False] * (n + 1)
can_break[0] = True # the empty prefix needs no words
for end in range(1, n + 1):
# Try each possible last word s[start:end]; no word is longer than `longest`.
for start in range(max(0, end - longest), end):
if can_break[start] and s[start:end] in words:
can_break[end] = True
break
return can_break[n]