Word break
Medium TimeO(n²·m) SpaceO(n)
Given a string s and a dictionary words, say whether s can be cut entirely into dictionary words. Every character must be used and every piece must be a word, words may be reused as often as needed, and an empty string is breakable, trivially.
Examples
Example 1
- Input
- s = "applepenapple"dictionary = ["apple", "pen"]
- Output
trueapple,pen,apple—appleis used twice, which is allowed.
Example 2
- Input
- s = "catsandog"dictionary = ["cats", "dog", "sand", "and", "cat"]
- Output
falsecat sandandcats andboth leaveog, which is not in the dictionary.
The Code
function wordBreak(s, dictionary) {
const reachable = new Array(s.length + 1).fill(false);
reachable[0] = true;
for (let end = 1; end <= s.length; end++) {
for (let start = 0; start < end; start++) {
if (!reachable[start]) continue;
const piece = s.slice(start, end);
if (dictionary.indexOf(piece) !== -1) {
reachable[end] = true;
break;
}
}
}
return reachable[s.length];
}
wordBreak("applepenapple", ["apple", "pen"]);Done
The first 18 calls, of 109. This one does not fit on a page.
More like this
All dynamic programming examples (20) →- Climbing stairs Count the ways to the top — Fibonacci in disguise.
- Coin change Try every coin and keep the cheapest way to make the amount.
- Max subarray One pass, two running totals — Kadane’s algorithm.
- LCS Match a character or drop one from either string.
- Edit distance Insert, delete, or replace — take the cheapest at each mismatch.
- 0/1 Knapsack For each item, take it or leave it — keep the more valuable branch.