Word Break
Decide whether a string can be cut into words from a dictionary, where a word may be used more than once.
Given a string swordDicts
Example 1
Output: true
Explanation: "sunflower" is "sun" followed by "flower".
Example 2
Output: true
Explanation: "apple" is used twice.
Example 3
Output: false
The Idea
Picture a sign painted with no spaces: CATSANDOG. To read it, you look for where one word ends and the next one begins. This problem asks the same thing: can swordDict
Example 1 is quick, because "sunflower" is "sun" and then "flower". Example 3 takes more tries. Starting with "cat" leaves "sandog", "sand" fits next, and that leaves "og", which no word matches. Starting with "cats" instead leaves "andog", "and" fits, and once again "og" is left over.
Two different starts ran into the same leftover. In a longer string this happens again and again, and trying every possible cut repeats the same work many times. So what really matters about a partly finished cut? Only where it stops. After "cat" + "sand" or after "cats" + "and", we stand at the same spot, just before "og", and the words that brought us there make no difference.
Number the gaps between the letters of "catsandog" as positions: position 0 is before the c, and position 9 is after the g. Call a position reachable when the letters before it can be cut into words. Look at the picture below.
Position 0 is reachable with no words at all, so the row labelled "can split up to here?" says yes under it. The words "cat" and "cats" start at position 0, which makes positions 3 and 4 yes. The word "sand" starts at 3 and "and" starts at 4, and both end at 7, so position 7 is yes as well.
Now look at the orange dashed "dog". It does end at position 9, the end of the string, but it starts at position 6, and position 6 is no. No other word ends at 9, so position 9 stays no, and the answer for Example 3 is false.
So a position is reachable when some word ends there and starts at an earlier position that is reachable. Each yes or no is built from the ones to its left, worked out once and kept. Solving the whole string this way, from stored answers for its shorter beginnings, is called dynamic programming.
Solution Approach
Turning that idea into code means settling four things: why trying every cut is slow, what each stored answer holds, how one answer is worked out from earlier ones, and how to look up words quickly. One optional change then skips checks that can never match.
Trying every cut
Why not simply try every way to cut the string? A method can take each word that matches the front of s
With the string "aaaaaaab" and the words "a", "aa" and "aaa", it gets much worse. There are 44 ways to cut the seven a's into those words, and every one of them ends at the same b, which no word matches. Keeping one yes or no per position, as in the picture, settles each position once, however many ways lead to it.
What each stored answer holds
What should be stored? One true or false per position, so a booleancanSplitscanSplit[i]
Where does it start? The first entry, canSplit[0]canSplit[n]
Working out one position
How is canSplit[i]canSplit[j]
One working j is enough, so the search for position i stops at the first one. The positions are decided from left to right, so every canSplit[j]
Looking up words
Each check asks whether a piece of sHashSet<String>wordswords.contains("sand")
Skipping starts that are too far back
This last change is optional. In Example 3 the longest words, "cats" and "sand", have four letters, so a last word that starts more than four positions before i can never match. Starting j at i minus the longest word length skips those checks and gives the same answers. It saves the most when the words are short and s
Java Solution
The method wordBreak
- First, copy
into awordDict namedHashSet withwords , so each word check is a set lookup.new HashSet<>(wordDict) - Create the
arrayboolean with n + 1 entries, where n iscanSplit , and sets.length() to true for the empty start.canSplit[0] - Decide the positions from left to right with two loops, one inside the other. The outer loop moves
from 1 to n, the position being decided. Inside, a second loop movesi from 0 to just beforej , the possible start of the last word.i - If
is true andcanSplit[j] containswords , sets.substring(j, i) to true andcanSplit[i] out of the inner loop. Thebreak test comes first, so no substring is made for a position that is not reachable.canSplit[j] - After both loops, return
, the answer for the whole string.canSplit[n]
The main
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class WordBreak {
public static boolean wordBreak(String s, List<String> wordDict) {
Set<String> words = new HashSet<>(wordDict);
int n = s.length();
boolean[] canSplit = new boolean[n + 1]; // canSplit[i]: the first i letters split
canSplit[0] = true; // no letters need no words
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
if (canSplit[j] && words.contains(s.substring(j, i))) {
canSplit[i] = true; // a word from j to i ends here
break;
}
}
}
return canSplit[n];
}
public static void main(String[] args) {
System.out.println(wordBreak("sunflower", List.of("sun", "flower")));
System.out.println(wordBreak("applepenapple", List.of("apple", "pen")));
System.out.println(wordBreak("catsandog", List.of("cats", "dog", "sand", "and", "cat")));
System.out.println(wordBreak("goalspecial", List.of("go", "goal", "special")));
System.out.println(wordBreak("aaaaaaab", List.of("a", "aa", "aaa")));
System.out.println(wordBreak("cat", List.of("cats")));
}
}
Running it prints:
true
true
false
true
false
false
The answers true, true and false on the top three lines match Examples 1 to 3. The fourth line, true for "goalspecial", is worth a closer look. A cut that always takes the shortest word matching at the front takes "go", then finds no word starting with "al" and gives up. The two loops also try "goal", which reaches position 4, and "special" carries on from there to position 11, the end.
The fifth line is false: however the seven a's are grouped, the b at the end is left over, because no word matches it. The last line is false too, because "cats" is one letter longer than "cat" and so never matches any piece of it.
The original implementation,
Complexity
The work is the two loops over pairs of positions, with a substring and a set lookup for each pair.
- Time: O(n³), because the loops try about n²/2 pairs of positions j and i in a string of n letters, and each
and hash lookup reads up to n letters.substring - Space: O(n) plus the word set, because
keeps one true or false for each of the n + 1 positions, and only one substring is made at a time.canSplit
Listing every possible cut instead of only answering true or false is