Word Break
Word Break is a medium 1-D Dynamic Programming problem from the Blind 75. The key pattern is 1-d dynamic programming, and a good solution runs in O(n · L) time.
Problem
Determine whether text can be segmented completely into reusable dictionary words.
Examples
Example 1
Input
{"text":"applepenapple","words":["apple","pen"]}Output
trueExample 2
Input
{"text":"duelcoder","words":["duel","coder","code"]}Output
trueExample 3
Input
{"text":"aaab","words":["a","aa"]}Output
falseApproach
Position i is reachable if some earlier reachable position j has a dictionary word between j and i. The whole string breaks if its end is reachable.
| Pattern | 1-D dynamic programming |
|---|---|
| Time | O(n · L) |
| Space | O(n) |
Watch out for
Limit j to the longest dictionary word to avoid useless checks.